2018-02-04 13:51:08 +00:00
|
|
|
package crowd
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"encoding/xml"
|
|
|
|
"fmt"
|
|
|
|
"io/ioutil"
|
|
|
|
"net/http"
|
|
|
|
"net/url"
|
2019-04-21 17:58:15 +00:00
|
|
|
"strings"
|
2018-02-04 13:51:08 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type authReq struct {
|
|
|
|
XMLName struct{} `xml:"password"`
|
|
|
|
Password string `xml:"value"`
|
|
|
|
}
|
|
|
|
|
|
|
|
// Authenticate a user & password against Crowd. Returns error on failure
|
|
|
|
// or account lockout. Success is a populated User with nil error.
|
|
|
|
func (c *Crowd) Authenticate(user string, pass string) (User, error) {
|
|
|
|
u := User{}
|
|
|
|
|
|
|
|
ar := authReq{Password: pass}
|
|
|
|
arEncoded, err := xml.Marshal(ar)
|
|
|
|
if err != nil {
|
|
|
|
return u, err
|
|
|
|
}
|
|
|
|
arBuf := bytes.NewBuffer(arEncoded)
|
|
|
|
|
|
|
|
v := url.Values{}
|
|
|
|
v.Set("username", user)
|
2019-04-21 17:58:15 +00:00
|
|
|
|
|
|
|
if !strings.HasSuffix(c.url, "/") {
|
|
|
|
c.url += "/"
|
|
|
|
}
|
|
|
|
|
2018-02-04 13:51:08 +00:00
|
|
|
url := c.url + "rest/usermanagement/1/authentication?" + v.Encode()
|
|
|
|
|
2019-04-21 17:58:15 +00:00
|
|
|
c.Client.Jar = c.cookies
|
2018-02-04 13:51:08 +00:00
|
|
|
req, err := http.NewRequest("POST", url, arBuf)
|
|
|
|
if err != nil {
|
|
|
|
return u, err
|
|
|
|
}
|
|
|
|
req.SetBasicAuth(c.user, c.passwd)
|
|
|
|
req.Header.Set("Accept", "application/xml")
|
|
|
|
req.Header.Set("Content-Type", "application/xml")
|
2019-04-21 17:58:15 +00:00
|
|
|
resp, err := c.Client.Do(req)
|
2018-02-04 13:51:08 +00:00
|
|
|
if err != nil {
|
|
|
|
return u, err
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
body, err := ioutil.ReadAll(resp.Body)
|
|
|
|
if err != nil {
|
|
|
|
return u, err
|
|
|
|
}
|
|
|
|
|
|
|
|
switch resp.StatusCode {
|
|
|
|
case 400:
|
|
|
|
er := Error{}
|
|
|
|
err = xml.Unmarshal(body, &er)
|
|
|
|
if err != nil {
|
|
|
|
return u, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return u, fmt.Errorf("%s", er.Reason)
|
|
|
|
case 200:
|
|
|
|
err = xml.Unmarshal(body, &u)
|
|
|
|
if err != nil {
|
|
|
|
return u, err
|
|
|
|
}
|
|
|
|
default:
|
2019-04-21 17:58:15 +00:00
|
|
|
return u, fmt.Errorf("request failed: %s", resp.Status)
|
2018-02-04 13:51:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return u, nil
|
|
|
|
}
|