Browse Source
controllers: Added user controller with two endpoints mostly implemented.
login_bugfix
controllers: Added user controller with two endpoints mostly implemented.
login_bugfix
Gisle Aune
5 years ago
1 changed files with 70 additions and 0 deletions
@ -0,0 +1,70 @@ |
|||
package controllers |
|||
|
|||
import ( |
|||
"encoding/json" |
|||
"net/http" |
|||
|
|||
"git.aiterp.net/lucifer/lucifer/internal/respond" |
|||
"git.aiterp.net/lucifer/lucifer/models" |
|||
"github.com/gorilla/mux" |
|||
) |
|||
|
|||
// The UserController is a controller for all user inports.
|
|||
type UserController struct { |
|||
users models.UserRepository |
|||
} |
|||
|
|||
// getUsers (`GET /`): List users
|
|||
func (c *UserController) getUsers(w http.ResponseWriter, r *http.Request) { |
|||
// TODO: Check session
|
|||
|
|||
users, err := c.users.List(r.Context()) |
|||
if err != nil { |
|||
respond.Error(w, 500, "db_error", err.Error()) |
|||
return |
|||
} |
|||
|
|||
respond.JSON(w, 200, users) |
|||
} |
|||
|
|||
// login (`POST /login`): Log in as user
|
|||
func (c *UserController) login(w http.ResponseWriter, r *http.Request) { |
|||
loginData := struct { |
|||
Username string `json:"username"` |
|||
Password string `json:"password"` |
|||
}{} |
|||
|
|||
err := json.NewDecoder(r.Body).Decode(&loginData) |
|||
if err != nil { |
|||
respond.Error(w, 400, "invalid_json", "Input is not valid JSON.") |
|||
return |
|||
} |
|||
|
|||
user, err := c.users.FindByName(r.Context(), loginData.Username) |
|||
if err != nil { |
|||
respond.Error(w, http.StatusUnauthorized, "login_failed", "Login failed.") |
|||
return |
|||
} |
|||
|
|||
if err := user.CheckPassword(loginData.Password); err != nil { |
|||
respond.Error(w, http.StatusUnauthorized, "login_failed", "Login failed.") |
|||
return |
|||
} |
|||
|
|||
// TODO: Open session
|
|||
|
|||
respond.JSON(w, 200, user) |
|||
} |
|||
|
|||
// Mount mounts the controller
|
|||
func (c *UserController) Mount(router *mux.Router, prefix string) { |
|||
sub := router.PathPrefix(prefix).Subrouter() |
|||
|
|||
sub.Handle("/", http.HandlerFunc(c.getUsers)).Methods("GET") |
|||
sub.Handle("/login", http.HandlerFunc(c.login)).Methods("POST") |
|||
} |
|||
|
|||
// NewUserController creates a new UserController.
|
|||
func NewUserController(users models.UserRepository) *UserController { |
|||
return &UserController{users: users} |
|||
} |
Write
Preview
Loading…
Cancel
Save
Reference in new issue