Skip to content

Instantly share code, notes, and snippets.

@eamonnmcevoy
Last active February 5, 2018 23:04
Show Gist options
  • Save eamonnmcevoy/53bf89d3d5ee5edf3d3de3b5c272d8e6 to your computer and use it in GitHub Desktop.
Save eamonnmcevoy/53bf89d3d5ee5edf3d3de3b5c272d8e6 to your computer and use it in GitHub Desktop.
login endpoint
package root
type Credentials struct {
Username string `json:"username"`
Password string `json:"password"`
}
type UserService interface {
...
Login(c Credentials) (error, User)
}
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
}
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