Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Permissions for users #52

Merged
merged 5 commits into from
Mar 20, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions admin/handlers-get.go
Original file line number Diff line number Diff line change
Expand Up @@ -1077,6 +1077,38 @@ func usersGETHandler(w http.ResponseWriter, r *http.Request) {
incMetric(metricAdminOK)
}

// Handler for platform/environment stats in JSON
func permissionsGETHandler(w http.ResponseWriter, r *http.Request) {
incMetric(metricAdminReq)
utils.DebugHTTPDump(r, settingsmgr.DebugHTTP(settings.ServiceAdmin), false)
vars := mux.Vars(r)
// Extract username and verify
usernameVar, ok := vars["username"]
if !ok || !adminUsers.Exists(usernameVar) {
if settingsmgr.DebugService(settings.ServiceAdmin) {
log.Printf("DebugService: error getting username")
}
return
}
// Get context data
ctx := r.Context().Value(contextKey("session")).(contextValue)
javuto marked this conversation as resolved.
Show resolved Hide resolved
// Check permissions
if !checkAdminLevel(ctx[ctxLevel]) {
incMetric(metricAdminErr)
log.Println("insuficient permissions")
return
}
// Get permissions
permissions, err := adminUsers.GetPermissions(usernameVar)
if err != nil {
incMetric(metricAdminErr)
log.Printf("error getting permissions %v", err)
}
// Serve JSON
utils.HTTPResponse(w, utils.JSONApplicationUTF8, http.StatusOK, permissions)
incMetric(metricJSONOK)
}

// Handler for GET requests to download carves
func carvesDownloadHandler(w http.ResponseWriter, r *http.Request) {
incMetric(metricAdminReq)
Expand Down
88 changes: 87 additions & 1 deletion admin/handlers-post.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"github.com/jmpsec/osctrl/environments"
"github.com/jmpsec/osctrl/queries"
"github.com/jmpsec/osctrl/settings"
"github.com/jmpsec/osctrl/users"
"github.com/jmpsec/osctrl/utils"

"github.com/gorilla/mux"
Expand Down Expand Up @@ -1125,7 +1126,7 @@ func usersPOSTHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("DebugService: %s %v", responseMessage, err)
}
}
if newUser.Admin {
if u.Token {
token, exp, err := adminUsers.CreateToken(newUser.Username, jwtConfig.HoursToExpire, jwtConfig.JWTSecret)
if err != nil {
responseMessage = "error creating token"
Expand Down Expand Up @@ -1204,6 +1205,24 @@ func usersPOSTHandler(w http.ResponseWriter, r *http.Request) {
}
}
if u.Admin {
namesEnvs, err := envs.Names()
if err != nil {
responseMessage = "error getting environments"
responseCode = http.StatusInternalServerError
if settingsmgr.DebugService(settings.ServiceAdmin) {
log.Printf("DebugService: %s %v", responseMessage, err)
}
goto send_response
}
perms := adminUsers.GenPermissions(namesEnvs, u.Admin)
if err := adminUsers.ChangePermissions(u.Username, perms); err != nil {
responseMessage = "error changing permissions"
responseCode = http.StatusInternalServerError
if settingsmgr.DebugService(settings.ServiceAdmin) {
log.Printf("DebugService: %s %v", responseMessage, err)
}
goto send_response
}
token, exp, err := adminUsers.CreateToken(u.Username, jwtConfig.HoursToExpire, jwtConfig.JWTSecret)
if err != nil {
responseMessage = "error creating token"
Expand Down Expand Up @@ -1242,6 +1261,73 @@ send_response:
incMetric(metricAdminOK)
}

// Handler for POST request for /users/permissions
func permissionsPOSTHandler(w http.ResponseWriter, r *http.Request) {
incMetric(metricAdminReq)
responseMessage := "OK"
responseCode := http.StatusOK
utils.DebugHTTPDump(r, settingsmgr.DebugHTTP(settings.ServiceAdmin), true)
vars := mux.Vars(r)
// Extract username and verify
usernameVar, ok := vars["username"]
if !ok || !adminUsers.Exists(usernameVar) {
if settingsmgr.DebugService(settings.ServiceAdmin) {
log.Printf("DebugService: error getting username")
}
return
}
var p PermissionsRequest
// Get context data
ctx := r.Context().Value(contextKey("session")).(contextValue)
// Check permissions
if !checkAdminLevel(ctx[ctxLevel]) {
responseMessage = "insuficient permissions"
responseCode = http.StatusForbidden
log.Printf("%s has %s", ctx[ctxUser], responseMessage)
goto send_response
}
// Parse request JSON body
if settingsmgr.DebugService(settings.ServiceAdmin) {
log.Println("DebugService: Decoding POST body")
}
if err := json.NewDecoder(r.Body).Decode(&p); err != nil {
responseMessage = "error parsing POST body"
responseCode = http.StatusInternalServerError
if settingsmgr.DebugService(settings.ServiceAdmin) {
log.Printf("DebugService: %s %v", responseMessage, err)
}
javuto marked this conversation as resolved.
Show resolved Hide resolved
} else {
// Check CSRF Token
if checkCSRFToken(ctx[ctxCSRF], p.CSRFToken) {
javuto marked this conversation as resolved.
Show resolved Hide resolved
// TODO verify environments
perms := users.UserPermissions{
Environments: p.Environments,
Query: p.Query,
Carve: p.Carve,
}
if err := adminUsers.ChangePermissions(usernameVar, perms); err != nil {
responseMessage = "error changing permissions"
responseCode = http.StatusInternalServerError
log.Printf("%s has %s", ctx[ctxUser], responseMessage)
goto send_response
}
} else {
responseMessage = "invalid CSRF token"
responseCode = http.StatusInternalServerError
if settingsmgr.DebugService(settings.ServiceAdmin) {
log.Printf("DebugService: %s %v", responseMessage, err)
}
}
}
send_response:
javuto marked this conversation as resolved.
Show resolved Hide resolved
// Serialize and send response
if settingsmgr.DebugService(settings.ServiceAdmin) {
log.Println("DebugService: Users response sent")
}
utils.HTTPResponse(w, utils.JSONApplicationUTF8, responseCode, AdminResponse{Message: responseMessage})
incMetric(metricAdminOK)
}

// Handler POST requests enroll data
func enrollPOSTHandler(w http.ResponseWriter, r *http.Request) {
incMetric(metricAdminReq)
Expand Down
2 changes: 2 additions & 0 deletions admin/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,8 @@ func main() {
// Admin: manage users
routerAdmin.Handle("/users", handlerAuthCheck(http.HandlerFunc(usersGETHandler))).Methods("GET")
routerAdmin.Handle("/users", handlerAuthCheck(http.HandlerFunc(usersPOSTHandler))).Methods("POST")
routerAdmin.Handle("/users/permissions/{username}", handlerAuthCheck(http.HandlerFunc(permissionsGETHandler))).Methods("GET")
routerAdmin.Handle("/users/permissions/{username}", handlerAuthCheck(http.HandlerFunc(permissionsPOSTHandler))).Methods("POST")
// Admin: manage tokens
routerAdmin.Handle("/tokens/{username}", handlerAuthCheck(http.HandlerFunc(tokensGETHandler))).Methods("GET")
routerAdmin.Handle("/tokens/{username}/refresh", handlerAuthCheck(http.HandlerFunc(tokensPOSTHandler))).Methods("POST")
Expand Down
29 changes: 29 additions & 0 deletions admin/static/js/functions.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,32 @@
function sendGetRequest(req_url, _modal, _callback) {
$.ajax({
url: req_url,
dataType: 'json',
type: 'GET',
contentType: 'application/json',
success: function (data, textStatus, jQxhr) {
console.log('OK');
console.log(data);
if (_modal) {
$("#successModalMessage").text(data.message);
$("#successModal").modal();
}
if (_callback) {
_callback(data);
}
},
error: function (jqXhr, textStatus, errorThrown) {
var _clientmsg = 'Client: ' + errorThrown;
var _serverJSON = $.parseJSON(jqXhr.responseText);
var _servermsg = 'Server: ' + _serverJSON.message;
$("#errorModalMessageClient").text(_clientmsg);
console.log(_clientmsg);
$("#errorModalMessageServer").text(_servermsg);
$("#errorModal").modal();
}
});
}

function sendPostRequest(req_data, req_url, _redir, _modal, _callback) {
$.ajax({
url: req_url,
Expand Down
62 changes: 61 additions & 1 deletion admin/static/js/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ function confirmAddUser() {
var _email = $("#user_email").val();
var _fullname = $("#user_fullname").val();
var _password = $("#user_password").val();
var _admin = $("#user_admin").is(':checked');
var _token = $("#user_token").is(':checked');

var data = {
csrftoken: _csrftoken,
Expand All @@ -23,7 +25,8 @@ function confirmAddUser() {
email: _email,
fullname: _fullname,
password: _password,
admin: false
admin: _admin,
token: _token
};
sendPostRequest(data, _url, _url, false);
}
Expand All @@ -42,6 +45,12 @@ function changeAdminUser(_user) {
var _csrftoken = $("#csrftoken").val();
var _value = $("#" + _user).is(':checked');

if (_value) {
$('#permissions-button-' + _user).hide();
} else {
$('#permissions-button-' + _user).show();
}

var _url = window.location.pathname;

var data = {
Expand Down Expand Up @@ -91,3 +100,54 @@ function refreshUserToken() {
$("#refreshTokenButton").text('Refresh');
});
}

function showPermissions(_username) {
$("#username_permissions").val(_username);
sendGetRequest('/users/permissions/' + _username, false, function (data) {
$('.switch-env-permission').each(function () {
var _env = $(this).attr('id');
if (data.environments) {
if (data.environments[_env]) {
$(this).attr('checked', true);
} else {
$(this).attr('checked', false);
}
} else {
$(this).attr('checked', false);
}
});
if (data.query) {
$("#permission-queries").attr('checked', true);
} else {
$("#permission-queries").attr('checked', false);
}
if (data.carve) {
$("#permission-carves").attr('checked', true);
} else {
$("#permission-carves").attr('checked', false);
}
});
$("#permissionsModal").modal();
}

function savePermissions() {
var _csrftoken = $("#csrftoken").val();
var _username = $("#username_permissions").val();

var _queries = $("#permission-queries").is(':checked');
var _carves = $("#permission-carves").is(':checked');

var _envs = {};
$('.switch-env-permission').each(function () {
_envs[$(this).attr('id')] = $(this).prop('checked');
});
var data = {
csrftoken: _csrftoken,
environments: _envs,
query: _queries,
carve: _carves,
};
sendPostRequest(data, '/users/permissions/' + _username, '', false, function (data) {
console.log(data);
});
}
Loading