netmaker/controllers/user.go

494 lines
14 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"
2022-09-14 03:25:56 +08:00
"github.com/gorilla/websocket"
2021-10-22 03:28:58 +08:00
"github.com/gravitl/netmaker/auth"
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"
2022-09-14 03:25:56 +08:00
"github.com/gravitl/netmaker/servercfg"
)
var (
upgrader = websocket.Upgrader{}
2021-03-26 00:17:52 +08:00
)
func userHandlers(r *mux.Router) {
r.HandleFunc("/api/users/adm/hasadmin", hasAdmin).Methods(http.MethodGet)
r.HandleFunc("/api/users/adm/createadmin", createAdmin).Methods(http.MethodPost)
r.HandleFunc("/api/users/adm/authenticate", authenticateUser).Methods(http.MethodPost)
r.HandleFunc("/api/users/{username}", logic.SecurityCheck(false, logic.ContinueIfUserMatch(http.HandlerFunc(updateUser)))).Methods(http.MethodPut)
r.HandleFunc("/api/users/networks/{username}", logic.SecurityCheck(true, http.HandlerFunc(updateUserNetworks))).Methods(http.MethodPut)
r.HandleFunc("/api/users/{username}/adm", logic.SecurityCheck(true, http.HandlerFunc(updateUserAdm))).Methods(http.MethodPut)
r.HandleFunc("/api/users/{username}", logic.SecurityCheck(true, checkFreeTierLimits(users_l, http.HandlerFunc(createUser)))).Methods(http.MethodPost)
r.HandleFunc("/api/users/{username}", logic.SecurityCheck(true, http.HandlerFunc(deleteUser))).Methods(http.MethodDelete)
r.HandleFunc("/api/users/{username}", logic.SecurityCheck(false, logic.ContinueIfUserMatch(http.HandlerFunc(getUser)))).Methods(http.MethodGet)
r.HandleFunc("/api/users", logic.SecurityCheck(true, http.HandlerFunc(getUsers))).Methods(http.MethodGet)
r.HandleFunc("/api/oauth/login", auth.HandleAuthLogin).Methods(http.MethodGet)
r.HandleFunc("/api/oauth/callback", auth.HandleAuthCallback).Methods(http.MethodGet)
2023-01-02 15:48:40 +08:00
r.HandleFunc("/api/oauth/headless", auth.HandleHeadlessSSO)
2023-04-13 23:36:13 +08:00
r.HandleFunc("/api/oauth/register/{regKey}", auth.RegisterHostSSO).Methods(http.MethodGet)
2021-03-26 00:17:52 +08:00
}
// swagger:route POST /api/users/adm/authenticate user authenticateUser
2022-09-06 20:20:24 +08:00
//
// Node authenticates using its password and retrieves a JWT for authorization.
2022-09-06 20:20:24 +08:00
//
2023-01-02 15:48:40 +08:00
// Schemes: https
2022-09-06 20:20:24 +08:00
//
2023-01-02 15:48:40 +08:00
// Security:
// oauth
2022-09-06 20:20:24 +08:00
//
2023-01-02 15:48:40 +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.",
}
2022-09-14 03:25:56 +08:00
if !servercfg.IsBasicAuthEnabled() {
2022-09-15 01:26:31 +08:00
logic.ReturnErrorResponse(response, request, logic.FormatError(fmt.Errorf("basic auth is disabled"), "badrequest"))
2022-09-14 03:25:56 +08:00
return
}
2021-04-18 02:03:01 +08:00
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())
2022-09-15 01:26:31 +08:00
logic.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())
2022-09-15 01:26:31 +08:00
logic.ReturnErrorResponse(response, request, logic.FormatError(err, "badrequest"))
2021-04-30 23:30:19 +08:00
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-09-15 01:26:31 +08:00
logic.ReturnErrorResponse(response, request, logic.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())
2022-09-15 01:26:31 +08:00
logic.ReturnErrorResponse(response, request, errorResponse)
2021-04-30 06:14:13 +08:00
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)
}
// swagger:route GET /api/users/adm/hasadmin user hasAdmin
2022-09-06 20:20:24 +08:00
//
// Checks whether the server has an admin.
//
2023-01-02 15:48:40 +08:00
// Schemes: https
2022-09-06 20:20:24 +08:00
//
2023-01-02 15:48:40 +08:00
// Security:
// oauth
2022-09-11 12:51:59 +08:00
//
2023-01-02 15:48:40 +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())
2022-09-15 01:26:31 +08:00
logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal"))
2021-08-10 01:30:40 +08:00
return
2021-09-06 22:36:14 +08:00
}
2021-03-26 00:17:52 +08:00
json.NewEncoder(w).Encode(hasadmin)
}
// swagger:route GET /api/users/{username} user getUser
2022-09-06 20:20:24 +08:00
//
// Get an individual user.
//
2023-01-02 15:48:40 +08:00
// Schemes: https
2022-09-06 20:20:24 +08:00
//
2023-01-02 15:48:40 +08:00
// Security:
// oauth
2022-09-11 12:51:59 +08:00
//
2023-01-02 15:48:40 +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())
2022-09-15 01:26:31 +08:00
logic.ReturnErrorResponse(w, r, logic.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)
}
// swagger:route GET /api/users user getUsers
2022-09-06 20:20:24 +08:00
//
2022-09-11 12:51:59 +08:00
// Get all users.
2022-09-06 20:20:24 +08:00
//
2023-01-02 15:48:40 +08:00
// Schemes: https
2022-09-06 20:20:24 +08:00
//
2023-01-02 15:48:40 +08:00
// Security:
// oauth
2022-09-11 12:51:59 +08:00
//
2023-01-02 15:48:40 +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())
2022-09-15 01:26:31 +08:00
logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal"))
return
}
2021-07-02 12:03:46 +08:00
2023-04-04 02:36:38 +08:00
logic.SortUsers(users[:])
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
}
// swagger:route POST /api/users/adm/createadmin user createAdmin
2022-09-06 20:20:24 +08:00
//
// Make a user an admin.
//
2023-01-02 15:48:40 +08:00
// Schemes: https
2022-09-06 20:20:24 +08:00
//
2023-01-02 15:48:40 +08:00
// Security:
// oauth
2022-09-11 12:51:59 +08:00
//
2023-01-02 15:48:40 +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())
2022-09-15 01:26:31 +08:00
logic.ReturnErrorResponse(w, r, logic.FormatError(err, "badrequest"))
return
}
2021-04-30 23:30:19 +08:00
2022-09-14 03:25:56 +08:00
if !servercfg.IsBasicAuthEnabled() {
2022-09-15 01:26:31 +08:00
logic.ReturnErrorResponse(w, r, logic.FormatError(fmt.Errorf("basic auth is disabled"), "badrequest"))
2022-09-14 03:25:56 +08:00
return
}
err = logic.CreateAdmin(&admin)
2021-04-18 02:03:01 +08:00
if err != nil {
logger.Log(0, admin.UserName, "failed to create admin: ",
err.Error())
2022-09-15 01:26:31 +08:00
logic.ReturnErrorResponse(w, r, logic.FormatError(err, "badrequest"))
2021-04-18 02:03:01 +08:00
return
}
2022-09-14 03:25:56 +08:00
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)
}
// swagger:route POST /api/users/{username} user createUser
2022-09-06 20:20:24 +08:00
//
// Create a user.
//
2023-01-02 15:48:40 +08:00
// Schemes: https
2022-09-06 20:20:24 +08:00
//
2023-01-02 15:48:40 +08:00
// Security:
// oauth
2022-09-11 12:51:59 +08:00
//
2023-01-02 15:48:40 +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())
2022-09-15 01:26:31 +08:00
logic.ReturnErrorResponse(w, r, logic.FormatError(err, "badrequest"))
return
}
2022-09-14 03:25:56 +08:00
err = logic.CreateUser(&user)
if err != nil {
logger.Log(0, user.UserName, "error creating new user: ",
err.Error())
2022-09-15 01:26:31 +08:00
logic.ReturnErrorResponse(w, r, logic.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
}
// swagger:route PUT /api/users/networks/{username} user updateUserNetworks
2022-09-06 20:20:24 +08:00
//
2022-09-11 12:51:59 +08:00
// Updates the networks of the given user.
2022-09-06 20:20:24 +08:00
//
2023-01-02 15:48:40 +08:00
// Schemes: https
2022-09-06 20:20:24 +08:00
//
2023-01-02 15:48:40 +08:00
// Security:
// oauth
2022-09-11 12:51:59 +08:00
//
2023-01-02 15:48:40 +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)
// start here
username := params["username"]
user, err := logic.GetUser(username)
if err != nil {
logger.Log(0, username,
"failed to update user networks: ", err.Error())
2022-09-15 01:26:31 +08:00
logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal"))
return
}
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())
2022-09-15 01:26:31 +08:00
logic.ReturnErrorResponse(w, r, logic.FormatError(err, "badrequest"))
return
}
err = logic.UpdateUserNetworks(userChange.Networks, userChange.Groups, userChange.IsAdmin, &models.ReturnUser{
2022-09-14 03:25:56 +08:00
Groups: user.Groups,
IsAdmin: user.IsAdmin,
Networks: user.Networks,
UserName: user.UserName,
})
if err != nil {
logger.Log(0, username,
"failed to update user networks: ", err.Error())
2022-09-15 01:26:31 +08:00
logic.ReturnErrorResponse(w, r, logic.FormatError(err, "badrequest"))
return
}
2021-12-07 04:31:08 +08:00
logger.Log(1, username, "status was updated")
// re-read and return the new user struct
if userChange, err = logic.GetUser(username); err != nil {
logger.Log(0, username, "failed to fetch user: ", err.Error())
logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal"))
return
}
json.NewEncoder(w).Encode(userChange)
}
// swagger:route PUT /api/users/{username} user updateUser
2022-09-06 20:20:24 +08:00
//
// Update a user.
//
2023-01-02 15:48:40 +08:00
// Schemes: https
2022-09-06 20:20:24 +08:00
//
2023-01-02 15:48:40 +08:00
// Security:
// oauth
2022-09-11 12:51:59 +08:00
//
2023-01-02 15:48:40 +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)
// start here
2023-04-03 21:54:16 +08:00
jwtUser, _, isadmin, err := logic.VerifyJWT(r.Header.Get("Authorization"))
2023-03-31 03:10:17 +08:00
if err != nil {
logger.Log(0, "verifyJWT error", err.Error())
logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal"))
return
}
2021-07-19 23:30:27 +08:00
username := params["username"]
2023-03-31 03:10:17 +08:00
if username != jwtUser && !isadmin {
logger.Log(0, "non-admin user", jwtUser, "attempted to update user", username)
logic.ReturnErrorResponse(w, r, logic.FormatError(errors.New("not authorizied"), "unauthorized"))
return
}
user, err := logic.GetUser(username)
2021-04-18 02:03:01 +08:00
if err != nil {
logger.Log(0, username,
"failed to update user info: ", err.Error())
2022-09-15 01:26:31 +08:00
logic.ReturnErrorResponse(w, r, logic.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())
2022-09-15 01:26:31 +08:00
logic.ReturnErrorResponse(w, r, logic.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())
2022-09-15 01:26:31 +08:00
logic.ReturnErrorResponse(w, r, logic.FormatError(err, "badrequest"))
2021-04-18 02:03:01 +08:00
return
}
2023-03-31 03:10:17 +08:00
if userchange.IsAdmin && !isadmin {
logger.Log(0, "non-admin user", jwtUser, "attempted get admin privilages")
logic.ReturnErrorResponse(w, r, logic.FormatError(errors.New("not authorizied"), "unauthorized"))
return
}
2021-07-02 12:03:46 +08:00
userchange.Networks = nil
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())
2022-09-15 01:26:31 +08:00
logic.ReturnErrorResponse(w, r, logic.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)
}
// swagger:route PUT /api/users/{username}/adm user updateUserAdm
2022-09-06 20:20:24 +08:00
//
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
//
2023-01-02 15:48:40 +08:00
// Schemes: https
2022-09-06 20:20:24 +08:00
//
2023-01-02 15:48:40 +08:00
// Security:
// oauth
2022-09-11 12:51:59 +08:00
//
2023-01-02 15:48:40 +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)
// start here
2021-07-19 23:30:27 +08:00
username := params["username"]
user, err := logic.GetUser(username)
if err != nil {
2022-09-15 01:26:31 +08:00
logic.ReturnErrorResponse(w, r, logic.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())
2022-09-15 01:26:31 +08:00
logic.ReturnErrorResponse(w, r, logic.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())
2022-09-15 01:26:31 +08:00
logic.ReturnErrorResponse(w, r, logic.FormatError(err, "badrequest"))
return
}
if !user.IsAdmin {
logger.Log(0, username, "not an admin user")
2022-09-15 01:26:31 +08:00
logic.ReturnErrorResponse(w, r, logic.FormatError(errors.New("not a admin user"), "badrequest"))
}
user, err = logic.UpdateUser(&userchange, user)
if err != nil {
logger.Log(0, username,
"failed to update user (admin) info: ", err.Error())
2022-09-15 01:26:31 +08:00
logic.ReturnErrorResponse(w, r, logic.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
}
// swagger:route DELETE /api/users/{username} user deleteUser
2022-09-06 20:20:24 +08:00
//
// Delete a user.
//
2023-01-02 15:48:40 +08:00
// Schemes: https
2022-09-06 20:20:24 +08:00
//
2023-01-02 15:48:40 +08:00
// Security:
// oauth
2022-09-11 12:51:59 +08:00
//
2023-01-02 15:48:40 +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())
2022-09-15 01:26:31 +08:00
logic.ReturnErrorResponse(w, r, logic.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())
2022-09-15 01:26:31 +08:00
logic.ReturnErrorResponse(w, r, logic.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.")
}
2022-09-14 03:25:56 +08:00
// Called when vpn client dials in to start the auth flow and first stage is to get register URL itself
func socketHandler(w http.ResponseWriter, r *http.Request) {
// Upgrade our raw HTTP connection to a websocket based one
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
2022-09-15 22:23:19 +08:00
logger.Log(0, "error during connection upgrade for node sign-in:", err.Error())
return
}
if conn == nil {
logger.Log(0, "failed to establish web-socket connection during node sign-in")
2022-09-14 03:25:56 +08:00
return
}
// Start handling the session
2023-04-13 23:36:13 +08:00
go auth.SessionHandler(conn)
2022-09-14 03:25:56 +08:00
}