|
| 1 | +package api |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "memos/common/error" |
| 6 | + "memos/store" |
| 7 | + "net/http" |
| 8 | + |
| 9 | + "github.com/gorilla/mux" |
| 10 | +) |
| 11 | + |
| 12 | +type UserSignUp struct { |
| 13 | + Username string `json:"username"` |
| 14 | + Password string `json:"password"` |
| 15 | +} |
| 16 | + |
| 17 | +func handleUserSignUp(w http.ResponseWriter, r *http.Request) { |
| 18 | + var userSignup UserSignUp |
| 19 | + err := json.NewDecoder(r.Body).Decode(&userSignup) |
| 20 | + |
| 21 | + if err != nil { |
| 22 | + error.ErrorHandler(w, "REQUEST_BODY_ERROR") |
| 23 | + return |
| 24 | + } |
| 25 | + |
| 26 | + user, err := store.CreateNewUser(userSignup.Username, userSignup.Password, "", "") |
| 27 | + |
| 28 | + if err != nil { |
| 29 | + error.ErrorHandler(w, "") |
| 30 | + return |
| 31 | + } |
| 32 | + |
| 33 | + json.NewEncoder(w).Encode(user) |
| 34 | +} |
| 35 | + |
| 36 | +type UserSignin struct { |
| 37 | + Username string `json:"username"` |
| 38 | + Password string `json:"password"` |
| 39 | +} |
| 40 | + |
| 41 | +func handleUserSignIn(w http.ResponseWriter, r *http.Request) { |
| 42 | + var userSignin UserSignin |
| 43 | + err := json.NewDecoder(r.Body).Decode(&userSignin) |
| 44 | + |
| 45 | + if err != nil { |
| 46 | + error.ErrorHandler(w, "") |
| 47 | + return |
| 48 | + } |
| 49 | + |
| 50 | + user, err := store.GetUserByUsernameAndPassword(userSignin.Username, userSignin.Password) |
| 51 | + |
| 52 | + if err != nil { |
| 53 | + error.ErrorHandler(w, "") |
| 54 | + return |
| 55 | + } |
| 56 | + |
| 57 | + userIdCookie := &http.Cookie{ |
| 58 | + Name: "user_id", |
| 59 | + Value: user.Id, |
| 60 | + MaxAge: 3600 * 24 * 30, |
| 61 | + } |
| 62 | + http.SetCookie(w, userIdCookie) |
| 63 | + |
| 64 | + json.NewEncoder(w).Encode(user) |
| 65 | +} |
| 66 | + |
| 67 | +func handleUserSignOut(w http.ResponseWriter, r *http.Request) { |
| 68 | + userIdCookie := &http.Cookie{ |
| 69 | + Name: "user_id", |
| 70 | + Value: "", |
| 71 | + MaxAge: 0, |
| 72 | + } |
| 73 | + http.SetCookie(w, userIdCookie) |
| 74 | +} |
| 75 | + |
| 76 | +func RegisterAuthRoutes(r *mux.Router) { |
| 77 | + authRouter := r.PathPrefix("/api/auth").Subrouter() |
| 78 | + |
| 79 | + authRouter.HandleFunc("/signup", handleUserSignUp).Methods("POST") |
| 80 | + authRouter.HandleFunc("/signin", handleUserSignIn).Methods("POST") |
| 81 | + authRouter.HandleFunc("/signout", handleUserSignOut).Methods("POST") |
| 82 | +} |
0 commit comments