netmaker/controllers/user.go

291 lines
8.5 KiB
Go
Raw Normal View History

2021-03-26 00:17:52 +08:00
package controller
import (
2021-04-18 02:03:01 +08:00
"encoding/json"
"errors"
"fmt"
2021-04-18 02:03:01 +08:00
"net/http"
"github.com/gorilla/mux"
2021-10-22 03:28:58 +08:00
"github.com/gravitl/netmaker/auth"
2021-07-22 06:55:19 +08:00
"github.com/gravitl/netmaker/database"
2021-12-07 04:31:08 +08:00
"github.com/gravitl/netmaker/logger"
2021-10-22 03:28:58 +08:00
"github.com/gravitl/netmaker/logic"
2021-04-18 02:03:01 +08:00
"github.com/gravitl/netmaker/models"
2021-03-26 00:17:52 +08:00
)
func userHandlers(r *mux.Router) {
2021-04-18 02:03:01 +08:00
r.HandleFunc("/api/users/adm/hasadmin", hasAdmin).Methods("GET")
r.HandleFunc("/api/users/adm/createadmin", createAdmin).Methods("POST")
r.HandleFunc("/api/users/adm/authenticate", authenticateUser).Methods("POST")
2021-12-07 23:56:39 +08:00
r.HandleFunc("/api/users/{username}", securityCheck(false, continueIfUserMatch(http.HandlerFunc(updateUser)))).Methods("PUT")
r.HandleFunc("/api/users/networks/{username}", securityCheck(true, http.HandlerFunc(updateUserNetworks))).Methods("PUT")
r.HandleFunc("/api/users/{username}/adm", securityCheck(true, http.HandlerFunc(updateUserAdm))).Methods("PUT")
r.HandleFunc("/api/users/{username}", securityCheck(true, http.HandlerFunc(createUser))).Methods("POST")
2021-12-29 00:23:38 +08:00
r.HandleFunc("/api/users/{username}", securityCheck(true, http.HandlerFunc(deleteUser))).Methods("DELETE")
2021-12-07 23:56:39 +08:00
r.HandleFunc("/api/users/{username}", securityCheck(false, continueIfUserMatch(http.HandlerFunc(getUser)))).Methods("GET")
r.HandleFunc("/api/users", securityCheck(true, http.HandlerFunc(getUsers))).Methods("GET")
2021-10-22 03:28:58 +08:00
r.HandleFunc("/api/oauth/login", auth.HandleAuthLogin).Methods("GET")
r.HandleFunc("/api/oauth/callback", auth.HandleAuthCallback).Methods("GET")
2021-03-26 00:17:52 +08:00
}
// Node authenticates using its password and retrieves a JWT for authorization.
2021-03-26 00:17:52 +08:00
func authenticateUser(response http.ResponseWriter, request *http.Request) {
// Auth request consists of Mac Address and Password (from node that is authorizing
// in case of Master, auth is ignored and mac is set to "mastermac"
2021-04-18 02:03:01 +08:00
var authRequest models.UserAuthParams
var errorResponse = models.ErrorResponse{
Code: http.StatusInternalServerError, Message: "W1R3: It's not you it's me.",
}
decoder := json.NewDecoder(request.Body)
decoderErr := decoder.Decode(&authRequest)
defer request.Body.Close()
if decoderErr != nil {
returnErrorResponse(response, request, errorResponse)
return
2021-04-30 06:14:13 +08:00
}
2021-10-22 08:32:23 +08:00
jwt, err := logic.VerifyAuthRequest(authRequest)
2021-04-30 06:14:13 +08:00
if err != nil {
2021-04-30 23:30:19 +08:00
returnErrorResponse(response, request, formatError(err, "badrequest"))
return
2021-04-30 06:14:13 +08:00
}
if jwt == "" {
// very unlikely that err is !nil and no jwt returned, but handle it anyways.
2021-04-30 23:30:19 +08:00
returnErrorResponse(response, request, formatError(errors.New("No token returned"), "internal"))
2021-04-30 06:14:13 +08:00
return
}
2021-07-19 23:30:27 +08:00
username := authRequest.UserName
2021-04-30 06:14:13 +08:00
var successResponse = models.SuccessResponse{
Code: http.StatusOK,
2021-07-19 23:30:27 +08:00
Message: "W1R3: Device " + username + " Authorized",
2021-04-30 06:14:13 +08:00
Response: models.SuccessfulUserLoginResponse{
AuthToken: jwt,
2021-07-19 23:30:27 +08:00
UserName: username,
2021-04-30 06:14:13 +08:00
},
}
// Send back the JWT
2021-04-30 06:14:13 +08:00
successJSONResponse, jsonError := json.Marshal(successResponse)
if jsonError != nil {
returnErrorResponse(response, request, errorResponse)
return
2021-03-26 00:17:52 +08:00
}
2021-12-07 04:31:08 +08:00
logger.Log(2, username, "was authenticated")
2021-04-30 06:14:13 +08:00
response.Header().Set("Content-Type", "application/json")
response.Write(successJSONResponse)
}
2021-03-26 00:17:52 +08:00
func hasAdmin(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
2021-10-22 03:28:58 +08:00
hasadmin, err := logic.HasAdmin()
2021-08-10 01:30:40 +08:00
if err != nil {
returnErrorResponse(w, r, formatError(err, "internal"))
return
2021-09-06 22:36:14 +08:00
}
2021-03-26 00:17:52 +08:00
json.NewEncoder(w).Encode(hasadmin)
}
// GetUserInternal - gets an internal user
2021-07-24 06:24:34 +08:00
func GetUserInternal(username string) (models.User, error) {
2021-03-26 00:17:52 +08:00
2021-04-18 02:03:01 +08:00
var user models.User
2021-07-22 06:55:19 +08:00
record, err := database.FetchRecord(database.USERS_TABLE_NAME, username)
if err != nil {
return user, err
}
if err = json.Unmarshal([]byte(record), &user); err != nil {
return models.User{}, err
}
2021-04-18 02:03:01 +08:00
return user, err
2021-03-26 00:17:52 +08:00
}
// Get an individual node. Nothin fancy here folks.
2021-03-26 00:17:52 +08:00
func getUser(w http.ResponseWriter, r *http.Request) {
// set header.
w.Header().Set("Content-Type", "application/json")
2021-04-18 02:03:01 +08:00
var params = mux.Vars(r)
2021-07-19 23:30:27 +08:00
usernameFetched := params["username"]
2021-10-22 03:28:58 +08:00
user, err := logic.GetUser(usernameFetched)
2021-03-26 00:17:52 +08:00
if err != nil {
returnErrorResponse(w, r, formatError(err, "internal"))
2021-03-26 00:17:52 +08:00
return
}
2021-12-07 04:31:08 +08:00
logger.Log(2, r.Header.Get("user"), "fetched user", usernameFetched)
2021-03-26 00:17:52 +08:00
json.NewEncoder(w).Encode(user)
}
// Get an individual node. Nothin fancy here folks.
2021-07-02 12:03:46 +08:00
func getUsers(w http.ResponseWriter, r *http.Request) {
// set header.
w.Header().Set("Content-Type", "application/json")
2021-07-02 12:03:46 +08:00
2021-10-22 03:28:58 +08:00
users, err := logic.GetUsers()
2021-07-02 12:03:46 +08:00
if err != nil {
returnErrorResponse(w, r, formatError(err, "internal"))
return
}
2021-07-02 12:03:46 +08:00
2021-12-07 04:31:08 +08:00
logger.Log(2, r.Header.Get("user"), "fetched users")
json.NewEncoder(w).Encode(users)
2021-07-02 12:03:46 +08:00
}
2021-03-26 00:17:52 +08:00
func createAdmin(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var admin models.User
// get node from body of request
2021-03-26 00:17:52 +08:00
_ = json.NewDecoder(r.Body).Decode(&admin)
2021-10-15 04:36:14 +08:00
2021-10-22 03:28:58 +08:00
admin, err := logic.CreateAdmin(admin)
2021-04-30 23:30:19 +08:00
2021-04-18 02:03:01 +08:00
if err != nil {
2021-04-30 23:30:19 +08:00
returnErrorResponse(w, r, formatError(err, "badrequest"))
2021-04-18 02:03:01 +08:00
return
}
2021-12-07 04:31:08 +08:00
logger.Log(1, admin.UserName, "was made a new admin")
2021-03-26 00:17:52 +08:00
json.NewEncoder(w).Encode(admin)
}
2021-07-02 12:03:46 +08:00
func createUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
2021-07-02 12:03:46 +08:00
var user models.User
// get node from body of request
_ = json.NewDecoder(r.Body).Decode(&user)
2021-07-02 12:03:46 +08:00
2021-10-22 03:28:58 +08:00
user, err := logic.CreateUser(user)
2021-07-02 12:03:46 +08:00
if err != nil {
returnErrorResponse(w, r, formatError(err, "badrequest"))
return
}
2021-12-07 04:31:08 +08:00
logger.Log(1, user.UserName, "was created")
json.NewEncoder(w).Encode(user)
2021-07-02 12:03:46 +08:00
}
func updateUserNetworks(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var params = mux.Vars(r)
var user models.User
// start here
username := params["username"]
user, err := GetUserInternal(username)
if err != nil {
returnErrorResponse(w, r, formatError(err, "internal"))
return
}
var userchange models.User
// we decode our body request params
err = json.NewDecoder(r.Body).Decode(&userchange)
if err != nil {
returnErrorResponse(w, r, formatError(err, "internal"))
return
}
err = logic.UpdateUserNetworks(userchange.Networks, userchange.IsAdmin, &user)
if err != nil {
returnErrorResponse(w, r, formatError(err, "badrequest"))
return
}
2021-12-07 04:31:08 +08:00
logger.Log(1, username, "status was updated")
json.NewEncoder(w).Encode(user)
}
2021-03-26 00:17:52 +08:00
func updateUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var params = mux.Vars(r)
var user models.User
// start here
2021-07-19 23:30:27 +08:00
username := params["username"]
2021-07-24 06:24:34 +08:00
user, err := GetUserInternal(username)
2021-04-18 02:03:01 +08:00
if err != nil {
returnErrorResponse(w, r, formatError(err, "internal"))
2021-04-18 02:03:01 +08:00
return
}
if auth.IsOauthUser(&user) == nil {
returnErrorResponse(w, r, formatError(fmt.Errorf("can not update user info for oauth user %s", username), "forbidden"))
return
}
2021-04-18 02:03:01 +08:00
var userchange models.User
// we decode our body request params
err = json.NewDecoder(r.Body).Decode(&userchange)
2021-03-26 00:17:52 +08:00
if err != nil {
returnErrorResponse(w, r, formatError(err, "internal"))
2021-04-18 02:03:01 +08:00
return
}
2021-07-02 12:03:46 +08:00
userchange.Networks = nil
2021-10-22 03:28:58 +08:00
user, err = logic.UpdateUser(userchange, user)
2021-03-26 00:17:52 +08:00
if err != nil {
2021-04-30 23:30:19 +08:00
returnErrorResponse(w, r, formatError(err, "badrequest"))
2021-03-26 00:17:52 +08:00
return
}
2021-12-07 04:31:08 +08:00
logger.Log(1, username, "was updated")
2021-03-26 00:17:52 +08:00
json.NewEncoder(w).Encode(user)
}
2021-07-02 12:03:46 +08:00
func updateUserAdm(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var params = mux.Vars(r)
var user models.User
// start here
2021-07-19 23:30:27 +08:00
username := params["username"]
2021-07-24 06:24:34 +08:00
user, err := GetUserInternal(username)
if err != nil {
returnErrorResponse(w, r, formatError(err, "internal"))
return
}
if auth.IsOauthUser(&user) != nil {
returnErrorResponse(w, r, formatError(fmt.Errorf("can not update user info for oauth user"), "forbidden"))
return
}
var userchange models.User
// we decode our body request params
err = json.NewDecoder(r.Body).Decode(&userchange)
if err != nil {
returnErrorResponse(w, r, formatError(err, "internal"))
return
}
2021-10-22 03:28:58 +08:00
user, err = logic.UpdateUser(userchange, user)
if err != nil {
returnErrorResponse(w, r, formatError(err, "badrequest"))
return
}
2021-12-07 04:31:08 +08:00
logger.Log(1, username, "was updated (admin)")
json.NewEncoder(w).Encode(user)
2021-07-02 12:03:46 +08:00
}
2021-03-26 00:17:52 +08:00
func deleteUser(w http.ResponseWriter, r *http.Request) {
// Set header
w.Header().Set("Content-Type", "application/json")
// get params
var params = mux.Vars(r)
2021-07-19 23:30:27 +08:00
username := params["username"]
2021-10-22 03:28:58 +08:00
success, err := logic.DeleteUser(username)
2021-03-26 00:17:52 +08:00
2021-04-15 10:59:25 +08:00
if err != nil {
2021-04-18 02:03:01 +08:00
returnErrorResponse(w, r, formatError(err, "internal"))
2021-03-26 00:17:52 +08:00
return
2021-04-15 10:59:25 +08:00
} else if !success {
2021-07-24 06:24:34 +08:00
returnErrorResponse(w, r, formatError(errors.New("delete unsuccessful."), "badrequest"))
2021-04-18 02:03:01 +08:00
return
}
2021-03-26 00:17:52 +08:00
2021-12-07 04:31:08 +08:00
logger.Log(1, username, "was deleted")
2021-03-26 00:17:52 +08:00
json.NewEncoder(w).Encode(params["username"] + " deleted.")
}