Last active
October 10, 2018 23:24
-
-
Save miguelfermin/7c714d4131fe54201604014235f50cbc to your computer and use it in GitHub Desktop.
go service snippet
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
router := httprouter.New() | |
router.POST("/api/login", httpHandler(login)) | |
func httpHandler(fn httpRouterFunc) httpRouterFunc { | |
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { | |
fn(w, r, ps) | |
} | |
} | |
func login(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { | |
// prepare input | |
credentials, err := credentialsFromRequest(r) | |
if err != nil { | |
http.Error(w, err.Error(), http.StatusBadRequest) | |
return | |
} | |
authenticator := auth.NewAuthenticator(authRepo) | |
reader := users.NewReader(usersRepo) | |
res, authErr := authenticator.Login(*credentials, reader) | |
if authErr != nil { | |
respondWithError(authErr, w) | |
return | |
} | |
respond(w, res) | |
} | |
func (auth authenticator) Login(cred models.Credentials, reader users.Reader) (*Response, *models.Error) { | |
users, err := reader.ReadByUsername(cred.Username) | |
if err != nil { | |
return nil, err | |
} | |
var match *models.User | |
for _, user := range users { | |
if crypto.CompareHashAndPassword(user.Password, cred.Password) { | |
match = &user | |
break | |
} | |
} | |
if match == nil { | |
return nil, &models.Error{StatusCode: 404, Message: "User Not Found"} | |
} | |
token, err := auth.repo.Insert(*match) | |
if err != nil { | |
return nil, &models.Error{StatusCode: 500, Message: err.Error()} | |
} | |
res := Response{User: match.Response(), AccessToken: *token} | |
return &res, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment