2018-07-25 13:06:31 +00:00
|
|
|
package gonextcloud
|
2018-07-05 10:50:56 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2019-07-13 23:49:50 +00:00
|
|
|
|
2018-07-05 10:50:56 +00:00
|
|
|
req "github.com/levigross/grequests"
|
|
|
|
)
|
|
|
|
|
2018-07-30 08:08:35 +00:00
|
|
|
var errUnauthorized = fmt.Errorf("login first")
|
2018-07-05 10:50:56 +00:00
|
|
|
|
2018-07-30 08:03:38 +00:00
|
|
|
// Login perform login and create a session with the Nextcloud API.
|
2019-07-22 14:17:11 +00:00
|
|
|
func (c *client) Login(username string, password string) error {
|
2018-07-05 10:50:56 +00:00
|
|
|
c.username = username
|
|
|
|
c.password = password
|
|
|
|
options := req.RequestOptions{
|
|
|
|
Headers: c.headers,
|
|
|
|
Auth: []string{c.username, c.password},
|
|
|
|
}
|
|
|
|
c.session = req.NewSession(&options)
|
2018-07-09 11:36:07 +00:00
|
|
|
// TODO What to do with capabilities ? (other thant connection validation)
|
2018-07-05 10:50:56 +00:00
|
|
|
u := c.baseURL.ResolveReference(routes.capabilities)
|
2018-07-24 18:26:12 +00:00
|
|
|
res, err := c.session.Get(u.String(), nil)
|
2018-07-05 10:50:56 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2019-07-22 14:40:42 +00:00
|
|
|
var r capabilitiesResponse
|
2018-07-24 18:26:12 +00:00
|
|
|
res.JSON(&r)
|
2019-07-22 14:40:42 +00:00
|
|
|
// No need to check for Ocs.meta.StatusCode as capabilities are always returned
|
2018-07-24 18:26:12 +00:00
|
|
|
c.capabilities = &r.Ocs.Data.Capabilities
|
2018-10-16 09:02:04 +00:00
|
|
|
c.version = &r.Ocs.Data.Version
|
2018-07-24 18:26:12 +00:00
|
|
|
// Check if authentication failed
|
|
|
|
if !c.loggedIn() {
|
2019-07-22 14:17:11 +00:00
|
|
|
e := APIError{Message: "authentication failed"}
|
2018-07-24 18:26:12 +00:00
|
|
|
return &e
|
2018-07-09 10:53:53 +00:00
|
|
|
}
|
2019-07-13 23:49:50 +00:00
|
|
|
// Create webdav client
|
2019-07-16 06:29:38 +00:00
|
|
|
c.webdav = newWebDav(c.baseURL.String()+"/remote.php/webdav", c.username, c.password)
|
2018-07-05 10:50:56 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2018-07-30 08:03:38 +00:00
|
|
|
// Logout logs out from the Nextcloud API, close the session and delete session's cookie
|
2019-07-22 14:17:11 +00:00
|
|
|
func (c *client) Logout() error {
|
2018-07-05 10:50:56 +00:00
|
|
|
c.session.CloseIdleConnections()
|
2018-07-25 13:06:31 +00:00
|
|
|
c.session.HTTPClient.Jar = nil
|
|
|
|
// Clear capabilities as it is used to check for valid authentication
|
|
|
|
c.capabilities = nil
|
2018-07-05 10:50:56 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-07-22 14:17:11 +00:00
|
|
|
func (c *client) loggedIn() bool {
|
2018-07-24 18:26:12 +00:00
|
|
|
// When authentication failed, capabilities doesn't contains core information
|
2018-07-25 13:06:31 +00:00
|
|
|
if c.capabilities == nil {
|
|
|
|
return false
|
|
|
|
}
|
2018-07-24 18:26:12 +00:00
|
|
|
return c.capabilities.Core.WebdavRoot != ""
|
2018-07-05 10:50:56 +00:00
|
|
|
}
|