Example #1
0
func dataCheckerHandler(c *web.C, next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Method == "POST" {
			if len(c.Env["body"].(*body).Data) == 0 {
				jsonapi.Error(w, jsonapi.ErrNoData)
				return
			}
		}

		next.ServeHTTP(w, r)
	})
}
Example #2
0
func currentUserHandler(c web.C, w http.ResponseWriter, r *http.Request) {
	u := new(User)
	ur := &UserRepo{u, c.Env["db"].(*sql.DB)}

	token, err := jwt.ParseFromRequest(r, func(token *jwt.Token) (interface{}, error) {
		return []byte(os.Getenv("PRIVATE_KEY")), nil
	})

	if err != nil {
		jsonapi.Error(w, jsonapi.ErrUnauthorized)
		return
	}

	err = ur.FetchByEmail(token.Claims["email"].(string))

	if err == nil && token.Valid {
		json.NewEncoder(w).Encode(newBody(User{Id: u.Id, Email: u.Email, Token: u.Token}))
	} else {
		jsonapi.Error(w, jsonapi.ErrUnauthorized)
	}
}
Example #3
0
func userCreationHandler(c web.C, w http.ResponseWriter, r *http.Request) {
	u := &c.Env["body"].(*body).Data[0]
	ur := &UserRepo{u, c.Env["db"].(*sql.DB)}

	err := ur.Create()
	if err != nil {
		jsonapi.Error(w, err)
		return
	}

	w.WriteHeader(201)
	json.NewEncoder(w).Encode(newBody(User{Id: u.Id, Email: u.Email, Token: u.Token}))
}
Example #4
0
func sessionCreationHandler(c web.C, w http.ResponseWriter, r *http.Request) {
	reqUser := c.Env["body"].(*body).Data[0]
	u := new(User)
	ur := &UserRepo{u, c.Env["db"].(*sql.DB)}

	ur.FetchByEmail(reqUser.Email)

	err := u.Authenticate(reqUser.Password)
	if err != nil {
		jsonapi.Error(w, err)
		return
	}

	u.GenerateToken()

	err = ur.Update()
	if err != nil {
		jsonapi.Error(w, err)
		return
	}

	w.WriteHeader(201)
	json.NewEncoder(w).Encode(newBody(User{Id: u.Id, Email: u.Email, Token: u.Token}))
}