Ejemplo n.º 1
0
Archivo: auth.go Proyecto: nedmax/tsuru
func Login(w http.ResponseWriter, r *http.Request) error {
	var pass map[string]string
	err := json.NewDecoder(r.Body).Decode(&pass)
	if err != nil {
		return &errors.Http{Code: http.StatusBadRequest, Message: "Invalid JSON"}
	}
	password, ok := pass["password"]
	if !ok {
		msg := "You must provide a password to login"
		return &errors.Http{Code: http.StatusBadRequest, Message: msg}
	}
	if !validation.ValidateLength(password, passwordMinLen, passwordMaxLen) {
		return &errors.Http{Code: http.StatusPreconditionFailed, Message: passwordError}
	}
	u := auth.User{Email: r.URL.Query().Get(":email")}
	if !validation.ValidateEmail(u.Email) {
		return &errors.Http{Code: http.StatusPreconditionFailed, Message: emailError}
	}
	err = u.Get()
	if err != nil {
		return &errors.Http{Code: http.StatusNotFound, Message: "User not found"}
	}
	if u.Login(password) {
		t, _ := u.CreateToken()
		fmt.Fprintf(w, `{"token":"%s"}`, t.Token)
		return nil
	}
	msg := "Authentication failed, wrong password"
	return &errors.Http{Code: http.StatusUnauthorized, Message: msg}
}