netmaker/controllers/user.go

447 lines
12 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
}
2022-09-06 20:20:24 +08:00
// swagger:route POST /api/users/adm/authenticate nodes authenticateUser
//
// Node authenticates using its password and retrieves a JWT for authorization.
2022-09-06 20:20:24 +08:00
//
// Schemes: https
//
// Security:
// oauth
//
2022-09-11 12:51:59 +08:00
// Responses:
// 200: successResponse
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 {
logger.Log(0, "error decoding request body: ",
decoderErr.Error())
2021-04-18 02:03:01 +08:00
returnErrorResponse(response, request, errorResponse)
return
2021-04-30 06:14:13 +08:00
}
username := authRequest.UserName
2021-10-22 08:32:23 +08:00
jwt, err := logic.VerifyAuthRequest(authRequest)
2021-04-30 06:14:13 +08:00
if err != nil {
logger.Log(0, username, "user validation failed: ",
err.Error())
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.
logger.Log(0, username, "jwt token is empty")
2022-06-17 03:42:32 +08:00
returnErrorResponse(response, request, formatError(errors.New("no token returned"), "internal"))
2021-04-30 06:14:13 +08:00
return
}
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 {
logger.Log(0, username,
"error marshalling resp: ", err.Error())
2021-04-30 06:14:13 +08:00
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)
}
2022-09-06 20:20:24 +08:00
// swagger:route GET /api/users/adm/hasadmin nodes hasAdmin
//
// Checks whether the server has an admin.
//
// Schemes: https
//
// Security:
// oauth
2022-09-11 12:51:59 +08:00
//
// Responses:
// 200: successResponse
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 {
logger.Log(0, "failed to check for admin: ", err.Error())
2021-08-10 01:30:40 +08:00
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
}
2022-09-06 20:20:24 +08:00
// swagger:route GET /api/users/{username} nodes getUser
//
// Get an individual user.
//
// Schemes: https
//
// Security:
// oauth
2022-09-11 12:51:59 +08:00
//
// Responses:
// 200: userBodyResponse
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 {
logger.Log(0, usernameFetched, "failed to fetch user: ", err.Error())
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)
}
2022-09-06 20:20:24 +08:00
// swagger:route GET /api/users nodes getUsers
//
2022-09-11 12:51:59 +08:00
// Get all users.
2022-09-06 20:20:24 +08:00
//
// Schemes: https
//
// Security:
// oauth
2022-09-11 12:51:59 +08:00
//
// Responses:
// 200: userBodyResponse
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 {
logger.Log(0, "failed to fetch users: ", err.Error())
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
}
2022-09-06 20:20:24 +08:00
// swagger:route POST /api/users/adm/createadmin nodes createAdmin
//
// Make a user an admin.
//
// Schemes: https
//
// Security:
// oauth
2022-09-11 12:51:59 +08:00
//
// Responses:
// 200: userBodyResponse
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
2021-10-15 04:36:14 +08:00
err := json.NewDecoder(r.Body).Decode(&admin)
if err != nil {
logger.Log(0, admin.UserName, "error decoding request body: ",
err.Error())
returnErrorResponse(w, r, formatError(err, "badrequest"))
return
}
admin, err = logic.CreateAdmin(admin)
2021-04-30 23:30:19 +08:00
2021-04-18 02:03:01 +08:00
if err != nil {
logger.Log(0, admin.UserName, "failed to create admin: ",
err.Error())
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)
}
2022-09-06 20:20:24 +08:00
// swagger:route POST /api/users/{username} nodes createUser
//
// Create a user.
//
// Schemes: https
//
// Security:
// oauth
2022-09-11 12:51:59 +08:00
//
// Responses:
// 200: userBodyResponse
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
err := json.NewDecoder(r.Body).Decode(&user)
if err != nil {
logger.Log(0, user.UserName, "error decoding request body: ",
err.Error())
returnErrorResponse(w, r, formatError(err, "badrequest"))
return
}
user, err = logic.CreateUser(user)
if err != nil {
logger.Log(0, user.UserName, "error creating new user: ",
err.Error())
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
}
2022-09-06 20:20:24 +08:00
// swagger:route PUT /api/users/networks/{username} nodes updateUserNetworks
//
2022-09-11 12:51:59 +08:00
// Updates the networks of the given user.
2022-09-06 20:20:24 +08:00
//
// Schemes: https
//
// Security:
// oauth
2022-09-11 12:51:59 +08:00
//
// Responses:
// 200: userBodyResponse
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 {
logger.Log(0, username,
"failed to update user networks: ", err.Error())
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 {
logger.Log(0, username, "error decoding request body: ",
err.Error())
returnErrorResponse(w, r, formatError(err, "badrequest"))
return
}
err = logic.UpdateUserNetworks(userchange.Networks, userchange.IsAdmin, &user)
if err != nil {
logger.Log(0, username,
"failed to update user networks: ", err.Error())
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)
}
2022-09-06 20:20:24 +08:00
// swagger:route PUT /api/users/{username} nodes updateUser
//
// Update a user.
//
// Schemes: https
//
// Security:
// oauth
2022-09-11 12:51:59 +08:00
//
// Responses:
// 200: userBodyResponse
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 {
logger.Log(0, username,
"failed to update user info: ", err.Error())
returnErrorResponse(w, r, formatError(err, "internal"))
2021-04-18 02:03:01 +08:00
return
}
if auth.IsOauthUser(&user) == nil {
err := fmt.Errorf("cannot update user info for oauth user %s", username)
logger.Log(0, err.Error())
returnErrorResponse(w, r, formatError(err, "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 {
logger.Log(0, username, "error decoding request body: ",
err.Error())
returnErrorResponse(w, r, formatError(err, "badrequest"))
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 {
logger.Log(0, username,
"failed to update user info: ", err.Error())
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)
}
2022-09-06 20:20:24 +08:00
// swagger:route PUT /api/users/{username}/adm nodes updateUserAdm
//
2022-09-11 12:51:59 +08:00
// Updates the given admin user's info (as long as the user is an admin).
2022-09-06 20:20:24 +08:00
//
// Schemes: https
//
// Security:
// oauth
2022-09-11 12:51:59 +08:00
//
// Responses:
// 200: userBodyResponse
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 {
err := fmt.Errorf("cannot update user info for oauth user %s", username)
logger.Log(0, err.Error())
returnErrorResponse(w, r, formatError(err, "forbidden"))
return
}
var userchange models.User
// we decode our body request params
err = json.NewDecoder(r.Body).Decode(&userchange)
if err != nil {
logger.Log(0, username, "error decoding request body: ",
err.Error())
returnErrorResponse(w, r, formatError(err, "badrequest"))
return
}
if !user.IsAdmin {
logger.Log(0, username, "not an admin user")
returnErrorResponse(w, r, formatError(errors.New("not a admin user"), "badrequest"))
}
2021-10-22 03:28:58 +08:00
user, err = logic.UpdateUser(userchange, user)
if err != nil {
logger.Log(0, username,
"failed to update user (admin) info: ", err.Error())
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
}
2022-09-06 20:20:24 +08:00
// swagger:route DELETE /api/users/{username} nodes deleteUser
//
// Delete a user.
//
// Schemes: https
//
// Security:
// oauth
2022-09-11 12:51:59 +08:00
//
// Responses:
// 200: userBodyResponse
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-03-26 00:17:52 +08:00
success, err := logic.DeleteUser(username)
2021-04-15 10:59:25 +08:00
if err != nil {
logger.Log(0, username,
"failed to delete user: ", err.Error())
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 {
err := errors.New("delete unsuccessful")
logger.Log(0, username, err.Error())
returnErrorResponse(w, r, formatError(err, "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.")
}