gonextcloud/auth.go

60 lines
1.7 KiB
Go
Raw Normal View History

package gonextcloud
import (
"fmt"
req "github.com/levigross/grequests"
"github.com/studio-b12/gowebdav"
2018-10-26 13:35:50 +00:00
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types"
)
2018-07-30 08:08:35 +00:00
var errUnauthorized = fmt.Errorf("login first")
2018-07-30 08:03:38 +00:00
// Login perform login and create a session with the Nextcloud API.
func (c *Client) Login(username string, password string) error {
c.username = username
c.password = password
options := req.RequestOptions{
Headers: c.headers,
Auth: []string{c.username, c.password},
}
c.session = req.NewSession(&options)
// TODO What to do with capabilities ? (other thant connection validation)
u := c.baseURL.ResolveReference(routes.capabilities)
2018-07-24 18:26:12 +00:00
res, err := c.session.Get(u.String(), nil)
if err != nil {
return err
}
2018-07-24 18:26:12 +00:00
var r types.CapabilitiesResponse
res.JSON(&r)
// 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
c.version = &r.Ocs.Data.Version
2018-07-24 18:26:12 +00:00
// Check if authentication failed
if !c.loggedIn() {
e := types.APIError{Message: "authentication failed"}
return &e
2018-07-09 10:53:53 +00:00
}
// Create webdav client
c.webdav = gowebdav.NewClient(c.baseURL.String()+"/remote.php/webdav", c.username, c.password)
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
func (c *Client) Logout() error {
c.session.CloseIdleConnections()
c.session.HTTPClient.Jar = nil
// Clear capabilities as it is used to check for valid authentication
c.capabilities = nil
return nil
}
func (c *Client) loggedIn() bool {
2018-07-24 18:26:12 +00:00
// When authentication failed, capabilities doesn't contains core information
if c.capabilities == nil {
return false
}
2018-07-24 18:26:12 +00:00
return c.capabilities.Core.WebdavRoot != ""
}