Exemple #1
0
func createUserIdentificationMiddleware(userDao *users.Dao) routes.Middleware {
	return routes.MiddlewareFunc(func(w http.ResponseWriter, r *http.Request, context *routes.Context, next routes.HandlerFunc) {
		username, password, ok := r.BasicAuth()
		if ok {
			user, err := userDao.GetByUsername(username)
			if err != nil {
				log.Error("Failed to fetch user from datastore", log.Fields{
					"username": username,
					"error":    err,
				})

				w.WriteHeader(http.StatusInternalServerError)
				w.Write(toJson(Error{
					Message: "An internal server error has occurred.",
					Code:    CodeInternalError,
				}))

				return
			}

			if user != nil {
				if user.VerifyPassword(password) {
					context.User = user
				}
			} else {
				// TODO
			}
		}

		next(w, r, context)
	})
}
Exemple #2
0
func validateLoginRequest(r *http.Request, userDao *users.Dao) (*users.User, models.ValidationErrors, error) {
	errs := make(models.ValidationErrors)

	password := r.FormValue("password")
	if password == "" {
		errs.Add("Password", "This field is required.")
	}

	username := r.FormValue("username")
	var user *users.User
	if username == "" {
		errs.Add("Username", "This field is required.")
	}

	if username != "" && password != "" {
		var err error
		user, err = userDao.GetByUsername(username)
		if err != nil {
			return nil, nil, err
		}

		if user == nil || !user.VerifyPassword(password) {
			errs.Add("Username", "The username or password you have entered is invalid.")
		}
	}

	return user, errs, nil
}