Last active
February 5, 2018 23:04
-
-
Save eamonnmcevoy/53bf89d3d5ee5edf3d3de3b5c272d8e6 to your computer and use it in GitHub Desktop.
login endpoint
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package root | |
type Credentials struct { | |
Username string `json:"username"` | |
Password string `json:"password"` | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type UserService interface { | |
... | |
Login(c Credentials) (error, User) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func(ur* userRouter) loginHandler(w http.ResponseWriter, r *http.Request) { | |
log.Println("loginHandler") | |
err, credentials := decodeCredentials(r) | |
if err != nil { | |
Error(w, http.StatusBadRequest, "Invalid request payload") | |
return | |
} | |
var user root.User | |
err, user = ur.userService.Login(credentials) | |
if err == nil { | |
Json(w, http.StatusOK, user) | |
} else { | |
Error(w, http.StatusInternalServerError, "Incorrect password") | |
} | |
} | |
... | |
func decodeCredentials(r *http.Request) (error,root.Credentials) { | |
var c root.Credentials | |
if r.Body == nil { | |
return errors.New("no request body"), c | |
} | |
decoder := json.NewDecoder(r.Body) | |
err := decoder.Decode(&c) | |
return err, c | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func (p *UserService) Login(c root.Credentials) (error, root.User) { | |
model := userModel{} | |
err := p.collection.Find(bson.M{"username": c.Username}).One(&model) | |
err = model.comparePassword(c.Password) | |
if(err != nil) { | |
return err, root.User{} | |
} | |
return err, root.User{ | |
Id: model.Id.Hex(), | |
Username: model.Username, | |
Password: "-" } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment