package auth import ( "bytes" "encoding/json" "fmt" "log" "net/http" "path" "time" ) type LDAPUser struct { Username string `json:"username"` NumericId int `json:"id"` Name string `json:"name"` Surname string `json:"surname"` Email string `json:"email"` Role string `json:"role"` Gecos string `json:"gecos"` } func (u LDAPUser) GetUsername() string { return u.Username } func (u LDAPUser) GetName() string { return u.Name } func (u LDAPUser) GetSurname() string { return u.Surname } func (u LDAPUser) GetFullName() string { return u.Gecos } type SimpleSession struct { Token string `json:"token"` Username string `json:"username"` CreatedOn time.Time `json:"createdOn"` } func (s SimpleSession) GetUsername() string { return s.Username } func (s SimpleSession) GetToken() string { return s.Token } type LDAPAuthService struct { Host string } func (a *LDAPAuthService) doGetRequest(url string, response interface{}) error { req, err := http.NewRequest( "GET", path.Join(a.Host, "ldap", url), bytes.NewBuffer([]byte("")), ) if err != nil { log.Printf(`GET %q resulted in %v`, url, err) return err } res, err := http.DefaultClient.Do(req) if err != nil { log.Printf(`GET %q resulted in %v`, url, err) return err } if err := json.NewDecoder(res.Body).Decode(response); err != nil { log.Printf(`GET %q resulted in %v`, url, err) return err } return nil } func (a *LDAPAuthService) doPostRequest(url string, request interface{}, response interface{}) error { jsonStr, err := json.Marshal(request) if err != nil { return err } req, err := http.NewRequest("POST", path.Join(a.Host, "ldap", url), bytes.NewBuffer(jsonStr)) if err != nil { return err } req.Header.Set("Content-Type", "application/json") res, err := http.DefaultClient.Do(req) if err != nil { return err } return json.NewDecoder(res.Body).Decode(response) } func (a *LDAPAuthService) GetUser(username string) (User, error) { var user LDAPUser if err := a.doGetRequest(fmt.Sprintf("/user/%s", username), &user); err != nil { return nil, err } return &user, nil } func (a *LDAPAuthService) GetUsers() ([]User, error) { ldapUsers := []*LDAPUser{} if err := a.doGetRequest(fmt.Sprintf("/users"), &ldapUsers); err != nil { return nil, err } users := make([]User, len(ldapUsers)) for i, u := range ldapUsers { users[i] = u } return users, nil } func (a *LDAPAuthService) GetSession(token string) (Session, error) { var response SimpleSession if err := a.doGetRequest(fmt.Sprintf("/session/%s", token), &response); err != nil { return nil, err } return &response, nil } func (a *LDAPAuthService) Login(username, password string) (Session, error) { body := map[string]interface{}{ "username": username, "password": password, } var response SimpleSession if err := a.doPostRequest(fmt.Sprintf("/login"), body, &response); err != nil { return nil, err } return &response, nil }