public IActionResult Change([FromBody] JObject values) { string username = (string)values["username"]; string role = (string)values["role"]; try { using (var ctx = new UserContext()) { if (role.ToLower() != "user" && role.ToLower() != "admin") { return(BadRequest("NOT DONE: Role does not exist")); } else if (UserDatabaseAccess.CheckUser(ctx, username) == false) { return(BadRequest("NOT DONE: Username does not exist")); } else { UserDatabaseAccess.ChangeRole(ctx, username, role); return(Ok("DONE")); } } } catch { return(BadRequest("NOT DONE: An error occured")); } }
protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { #region Task5 // TODO: Find if a header ‘ApiKey’ exists, and if it does, check the database to determine if the given API Key is valid // Then authorise the principle on the current thread using a claim, claimidentity and claimsprinciple UserDatabaseAccess database = new UserDatabaseAccess(); IEnumerable <string> tempkey; request.Headers.TryGetValues("ApiKey", out tempkey); if (tempkey != null) { string APIKey = tempkey.First(); User temp = database.CheckKeyUser(APIKey); if (temp != null) { Claim name = new Claim(ClaimTypes.Name, temp.UserName); Claim type = new Claim(ClaimTypes.Role, temp.Role); ClaimsIdentity key = new ClaimsIdentity(temp.userID); key.AddClaim(name); key.AddClaim(type); ClaimsPrincipal cPrincipal = new ClaimsPrincipal(key); Thread.CurrentPrincipal = cPrincipal; } } #endregion return(base.SendAsync(request, cancellationToken)); }
protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // Task5 // TODO: Find if a header ‘ApiKey’ exists, and if it does, check the database to determine if the given API Key is valid // Then authorise the principle on the current thread using a claim, claimidentity and claimsprinciple UserDatabaseAccess userDatabaseAccess = new UserDatabaseAccess(); IEnumerable <string> values; request.Headers.TryGetValues("ApiKey", out values); if (values != null) { foreach (string v in values) { if (userDatabaseAccess.CheckApi(v)) { User user = userDatabaseAccess.CheckApiForUser(v); var claims = new List <Claim> { new Claim(ClaimTypes.Name, user.UserName, ClaimTypes.Role, user.UserRole.ToString()) }; var id = new ClaimsIdentity(claims, authenticationType: "ApiKey"); var principle = new ClaimsPrincipal(id); Thread.CurrentPrincipal = principle; } } } return(base.SendAsync(request, cancellationToken)); }
public HttpResponseMessage Get(HttpRequestMessage request, [FromUri] string message) { bool userExists = false; string response = "Bad Request"; HttpStatusCode statusCode = HttpStatusCode.BadRequest; string apiKey = request.Headers.GetValues("ApiKey").FirstOrDefault(); RSACryptoServiceProvider rsa = WebApiConfig.RSA; using (rsa) { if (userExists = UserDatabaseAccess.checkUserKey(apiKey)) { byte[] signedMessage; byte[] messageBytes = Encoding.ASCII.GetBytes(message); SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider(); signedMessage = rsa.SignData(messageBytes, sha1); response = BitConverter.ToString(signedMessage); statusCode = HttpStatusCode.OK; } } return(Request.CreateResponse <string>(statusCode, response)); }
protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { #region Task5 // TODO: Find if a header ‘ApiKey’ exists, and if it does, check the database to determine if the given API Key is valid // Then authorise the principle on the current thread using a claim, claimidentity and claimsprinciple if (request.Headers.TryGetValues("ApiKey", out IEnumerable <string> headerValues)) { if (UserDatabaseAccess.UserExists(new Guid(headerValues.FirstOrDefault()), out User user)) { UserDatabaseAccess.Log("User Requested " + request.RequestUri.ToString(), headerValues.First()); var claims = new List <Claim>(); claims.Add(new Claim(ClaimTypes.Name, user.UserName)); claims.Add(new Claim(ClaimTypes.Role, user.Role.ToString())); claims.Add(new Claim(ClaimTypes.Authentication, user.ApiKey)); ClaimsIdentity identity = new ClaimsIdentity("ApiKey"); identity.AddClaims(claims); ClaimsPrincipal principle = new ClaimsPrincipal(); principle.AddIdentity(new ClaimsIdentity(identity)); Thread.CurrentPrincipal = principle; } } return(base.SendAsync(request, cancellationToken)); #endregion }
public HttpResponseMessage Getsha256([FromUri] string message, HttpRequestMessage request) { string apiKey = request.Headers.GetValues("ApiKey").FirstOrDefault(); HttpStatusCode statusCode = HttpStatusCode.BadRequest; bool userExists = false; byte[] messageBytes; string response = "Bad Request"; byte[] responseBytes; if (message != null) { if (userExists = UserDatabaseAccess.checkUserKey(apiKey)) { messageBytes = Encoding.ASCII.GetBytes(message); SHA256 sha = new SHA256CryptoServiceProvider(); responseBytes = sha.ComputeHash(messageBytes); response = BitConverter.ToString(responseBytes).Replace("-", ""); statusCode = HttpStatusCode.OK; } } return(Request.CreateResponse <string>(statusCode, response)); }
protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { IEnumerable <string> key; request.Headers.TryGetValues("ApiKey", out key); if (key != null) { try { Guid keyValid = new Guid(key.FirstOrDefault()); } catch (Exception e) //Can be used to log if needed { return(base.SendAsync(request, cancellationToken)); //Don't send exception, user shouldn't get the error info. } UserDatabaseAccess dbUser = new UserDatabaseAccess(); if (dbUser.DoesUserExist(key.First())) { User user = dbUser.getUserIfExists(key.First()); Claim claim = new Claim("name", user.UserName); Claim[] claimants = new Claim[1] { claim }; ClaimsIdentity identity = new ClaimsIdentity(claimants, "ApiKey"); ClaimsPrincipal principle = new ClaimsPrincipal(identity); Thread.CurrentPrincipal = principle; } } return(base.SendAsync(request, cancellationToken)); }
public async Task <ActionResult <User> > PostUser([FromBody] string userName) { try { if (userName == "" || userName == null) { throw new Exception("Oops. Make sure your body contains a string with your username and your Content - Type is Content - Type:application / json"); } var userExists = await UserDatabaseAccess.UserExists(userName, base._context); if (userExists) //If the User entered Exists { return(StatusCode(403, "Oops. This username is already in use. Please try again with a new username.")); } var newUser = await UserDatabaseAccess.MakeUser(userName, base._context); return(StatusCode(200, newUser.ApiKey)); } catch (Exception e) { return(StatusCode(400, e.Message)); } }
protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { #region Task5 // TODO: Find if a header ‘ApiKey’ exists, and if it does, check the database to determine if the given API Key is valid // Then authorise the principle on the current thread using a claim, claimidentity and claimsprinciple #endregion if (request.Headers.Contains("ApiKey")) { string apiKeyHeaderValue = request.Headers.GetValues("ApiKey").FirstOrDefault(); if (apiKeyHeaderValue != null && UserDatabaseAccess.checkUserKey(apiKeyHeaderValue)) { if (UserDatabaseAccess.checkUserKey(apiKeyHeaderValue)) { User user = UserDatabaseAccess.checkUserRtnUsr(apiKeyHeaderValue); ClaimsPrincipal claimPrincipal = new ClaimsPrincipal(new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, user.UserName, ClaimValueTypes.String) }, "ApiKey")); Thread.CurrentPrincipal = claimPrincipal; } } } return(base.SendAsync(request, cancellationToken)); }
public IActionResult PostChangeRole([FromHeader] string Apikey, [FromBody] roleParams rp) { try { if (Enum.TryParse(rp.Role, out Role r)) { if (UserDatabaseAccess.UserChangeRole(_context, Apikey, rp.UserName, r)) { return(StatusCode(200, "DONE")); } else { return(StatusCode(400, "NOT DONE: Username does not exist")); } } else { return(StatusCode(400, "NOT DONE: Role does not exist")); } } catch { return(StatusCode(400, "NOT DONE: An error occured")); } }
public string POST([FromBody] User user) { string[] zoneStates = UserDatabaseAccess.getZoneState(); int zoneState = Int32.Parse(zoneStates[Int32.Parse(user.Zone)]); if (user.Team == "Blue Team") { if (zoneState > 0) { UserDatabaseAccess.updateDominance(Int32.Parse(user.Zone), user.Team, user.UserKey); } } else { if (zoneState < 100) { UserDatabaseAccess.updateDominance(Int32.Parse(user.Zone), user.Team, user.UserKey); } } string[] returnArray = UserDatabaseAccess.getZoneState(); string returnString = null; for (int i = 0; i < returnArray.Length; i++) { returnString = returnString + "," + returnArray[i]; } return(returnString); }
public IActionResult Delete([FromQuery] string username) { using (var pCtx = new UserContext()) { this.Request.Query.TryGetValue("username", out var pUserName); this.Request.Headers.TryGetValue("ApiKey", out var pApiKey); User newUser = UserDatabaseAccess.returnUserfromApi(pApiKey, pCtx); try//Used for testing { if (newUser == default) { return(Ok(false));//If newuser does not excist then return false } else if (newUser.APIKey == pApiKey && newUser.UserName == pUserName) { return(Ok(UserDatabaseAccess.removeUser(pApiKey, username, pCtx))); //If both match then use method to remove the user and return ok } else { return(Ok(UserDatabaseAccess.removeUser(pApiKey, username, pCtx))); } } catch (Exception e) { return(BadRequest("NOT DONE: An error occured")); } } }
public async Task <IActionResult> SignMessage([FromQuery] string Message, [FromHeader] string APIKey) { try { #region Register Log var user = await UserDatabaseAccess.GetUser(APIKey, base._context); string Method = this.HttpContext.Request.Method; string Path = this.HttpContext.Request.Path; var logString = user.Role + " requested " + Method + " " + Path; await UserDatabaseAccess.AddLog(logString, user, base._context); #endregion if (Message == null) { throw new Exception(); } var byteMessage = Encoding.ASCII.GetBytes(Message); var signedData = _RSA.SignData(byteMessage, new SHA1CryptoServiceProvider()); var hexMessage = EncryptionHelper.ByteArrayToHexString(signedData, true); return(StatusCode(200, hexMessage)); } catch (Exception) { return(StatusCode(400, "Bad Request")); } }
public async Task <IActionResult> GetSHA256([FromQuery] string message, [FromHeader] string APIKey) { try { #region Register Log var authUser = await UserDatabaseAccess.GetUser(APIKey, base._context); string Method = this.HttpContext.Request.Method; string Path = this.HttpContext.Request.Path; var Log = authUser.Role + " requested " + Method + " " + Path; await UserDatabaseAccess.AddLog(Log, authUser, base._context); #endregion if (message == null) { throw new Exception(); } SHA256 SHA1Provider = new SHA256CryptoServiceProvider(); byte[] ASCIIByteMessage = Encoding.ASCII.GetBytes(message); byte[] SHA1ByteMessage = SHA1Provider.ComputeHash(ASCIIByteMessage); string Encrypted = EncryptionHelper.ByteArrayToHexString(SHA1ByteMessage, false); return(StatusCode(200, Encrypted.ToUpper())); } catch (Exception) { return(StatusCode(400, "Bad Rquest")); } }
public ActionResult RemoveUser(string uname, [FromHeader] string key) { if (UserDatabaseAccess.userCheck(uname)) { if (UserDatabaseAccess.userApi(key, uname)) { if (UserDatabaseAccess.deleteUser(uname)) { return(Ok(true)); } else { return(Ok(false)); } } else { return(Ok("You cannot delete a user that is not yourself.")); } } else { return(Ok("There is no user with that username.")); } }
public async Task InvokeAsync(HttpContext context, Models.UserContext dbContext) { #region Task5 // TODO: Find if a header ‘ApiKey’ exists, and if it does, check the database to determine if the given API Key is valid // Then set the correct roles for the User, using claims var AuthAPIKey = context.Request.Headers["APIKey"].ToString(); var verifyKey = await UserDatabaseAccess.APIKeyExists(AuthAPIKey, dbContext); if (verifyKey) { var user = await UserDatabaseAccess.GetUser(AuthAPIKey, dbContext); if (user != null) { var claimArray = new Claim[] { new Claim(ClaimTypes.Name, user.UserName), new Claim(ClaimTypes.Role, user.Role) }; context.User.AddIdentity(new ClaimsIdentity(claimArray, "APIKey")); } } #endregion // Call the next delegate/middleware in the pipeline await _next(context); }
public async Task InvokeAsync(HttpContext context, Models.UserContext dbContext) { #region Task5 // TODO: Find if a header ‘ApiKey’ exists, and if it does, check the database to determine if the given API Key is valid // Then set the correct roles for the User, using claims //string apiKey = context.Request.Headers["ApiKey"].FirstOrDefault(); //fix this statement (auth works, just need to grab apikey correctly) string apiKey = context.Request.Headers.FirstOrDefault(a => a.Key == "ApiKey").Value.ToString(); var currentUser = UserDatabaseAccess.UserCheck_rObj(dbContext, apiKey); if (currentUser != null) //if user exists { var claimList = new List <Claim>() { new Claim(ClaimTypes.Name, currentUser.UserName), new Claim(ClaimTypes.Role, currentUser.Role.ToString()) }; var userId = new ClaimsIdentity(claimList, apiKey); context.User.AddIdentity(userId); } #endregion // Call the next delegate/middleware in the pipeline await _next(context); }
public async Task <ActionResult <User> > DeleteUser([FromHeader] string APIKey, [FromQuery] string userName) { try { if (await UserDatabaseAccess.APIKeyExists(APIKey, base._context)) { var user = await UserDatabaseAccess.GetUser(APIKey, base._context); #region Registering UserLog string Method = this.HttpContext.Request.Method; string Path = this.HttpContext.Request.Path; var logString = user.Role + " requested " + Method + " " + Path; await UserDatabaseAccess.AddLog(logString, user, base._context); #endregion if (user.ApiKey == APIKey && user.UserName == userName) { await UserDatabaseAccess.BackupLog(APIKey, base._context); await UserDatabaseAccess.RemoveUser(user, base._context); return(StatusCode(200, true)); } } throw new Exception(); } catch (Exception) { return(StatusCode(200, false)); } }
protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { //Task5 // TODO: Find if a header ‘ApiKey’ exists, and if it does, check the database to determine if the given API Key is valid // Then authorise the principle on the current thread using a claim, claimidentity and claimsprinciple if (request.Headers.Contains("ApiKey")) { string Key = request.Headers.GetValues("ApiKey").First(); var dbaccess = new UserDatabaseAccess(); if (dbaccess.CheckUserKey(Key)) { User user = dbaccess.UserCheckKey(Key); ClaimsIdentity identity = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, user.UserName), new Claim(ClaimTypes.Role, user.Role) }, Key); Thread.CurrentPrincipal = new ClaimsPrincipal(identity); return(await base.SendAsync(request, cancellationToken)); } } return(await base.SendAsync(request, cancellationToken)); }
public ActionResult protectedSHA256([FromHeader] string key, string message) { try { if (String.IsNullOrEmpty(message)) { if (UserDatabaseAccess.keyCheck(key)) { byte[] buffer = Encoding.ASCII.GetBytes(message); var sha = SHA256.Create(); var hash = sha.ComputeHash(buffer); return(Ok(hash)); } else { return(Ok()); } } else { return(new StatusCodeResult(StatusCodes.Status400BadRequest)); } } catch { return(new StatusCodeResult(StatusCodes.Status400BadRequest)); } }
public ActionResult publicKey([FromHeader] string key) { if (String.IsNullOrEmpty(key)) { throw new ArgumentNullException("Couldn't get the public key"); } if (UserDatabaseAccess.keyCheck(key)) { byte[] dataToChange = Encoding.ASCII.GetBytes(key); byte[] encrpyt; byte[] decryptData; RSAParameters publicKey; RSAParameters privateKey; string str; using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { rsa.PersistKeyInCsp = true; publicKey = rsa.ExportParameters(false); privateKey = rsa.ExportParameters(true); encrpyt = RSAInternal.RSAEncrypt(dataToChange, publicKey); str = RSACryptoExtensions.ToXmlStringCore22(rsa, false); decryptData = RSAInternal.RSADecrypt(encrpyt, privateKey); RSACryptoExtensions.FromXmlStringCore22(rsa, str); } return(Ok(str)); } else { return(Ok("ApiKey invalid")); } }
protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { #region Task5 // TODO: Find if a header ‘ApiKey’ exists, and if it does, check the database to determine if the given API Key is valid // Then authorise the principle on the current thread using a claim, claimidentity and claimsprinciple IEnumerable <string> headerValues; string headerKey = ""; if (request.Headers.TryGetValues("ApiKey", out headerValues)) { headerKey = headerValues.First(); UserDatabaseAccess accessor = new UserDatabaseAccess(); User existingUser = accessor.CheckandGetUserExists(headerKey); //Will check for user even if nothing exists as header key is "". //Maybe not the best idea for efficiency but it's ok for now. if (existingUser != null) { //Then the key is valid. Claim claim = new Claim(ClaimTypes.Name, existingUser.m_UserName); ClaimsIdentity identity = new ClaimsIdentity(new[] { claim }, "ApiKey"); ClaimsPrincipal principal = new ClaimsPrincipal(identity); Thread.CurrentPrincipal = principal; } } #endregion return(base.SendAsync(request, cancellationToken)); }
public HttpResponseMessage Post([FromBody] JObject username) { string user = username.GetValue("username").ToString(); string role = username.GetValue("role").ToString(); if (role == "User" || role == "Admin") { var dbaccess = new UserDatabaseAccess(); if (!dbaccess.CheckUserName(user)) { return(Request.CreateResponse(HttpStatusCode.BadRequest, "NOT DONE: Username does not exist")); } else if (dbaccess.ChangeRole(user, role)) { return(Request.CreateResponse(HttpStatusCode.OK, "DONE")); } else { return(Request.CreateResponse(HttpStatusCode.BadRequest, "NOT DONE: An error occured")); } } else { return(Request.CreateResponse(HttpStatusCode.BadRequest, "NOT DONE: Role does not exist")); } }
public async Task <IActionResult> GetPublicKey([FromHeader] string APIKey) { try { #region Register Log var user = await UserDatabaseAccess.GetUser(APIKey, base._context); string Method = this.HttpContext.Request.Method; string Path = this.HttpContext.Request.Path; var logString = user.Role + " requested " + Method + " " + Path; await UserDatabaseAccess.AddLog(logString, user, base._context); #endregion _RSA.ExportParameters(false); string xmlKey = _RSA.ToXmlStringCore22(false); return(StatusCode(200, xmlKey)); } catch (Exception) { return(StatusCode(400, "Bad Request")); } }
public string New([FromQuery] string username) { using (var ctx = new UserContext()) { return(UserDatabaseAccess.CheckUser(ctx, username) == true ? "True - User Does Exist! Did you mean to do a POST to create a new user?" : "False - User Does Not Exist! Did you mean to do a POST to create a new user?"); } }
public HttpResponseMessage Get() { string key = Request.Headers.GetValues("ApiKey").First(); var dbaccess = new UserDatabaseAccess(); dbaccess.KeyReturnUsername(key); { return(Request.CreateResponse(HttpStatusCode.OK, "Hello " + dbaccess.KeyReturnUsername(key))); } }
public HttpResponseMessage GET() { String[] resultArray = UserDatabaseAccess.getTopScores(); string result = null; for (int i = 0; i < resultArray.Length; i++) { result = result + "," + resultArray[i]; } return(Request.CreateResponse(HttpStatusCode.Accepted, result)); }
public IActionResult changeRole([FromBody] User user) { int code = 400; string message = UserDatabaseAccess.changeRole(user); if (message == "DONE") { code = 200; } return(StatusCode(code, message)); }
public IActionResult DeleteRemoveUser([FromHeader] string ApiKey, [FromQuery] string username) { if (UserDatabaseAccess.UserRemove(_context, ApiKey, username)) { return(StatusCode(200, "User deleted")); } else { return(StatusCode(200, "User not found")); } }
public HttpResponseMessage Get([FromUri] string username) { try { if (UserDatabaseAccess.UserExists(username)) { return(Request.CreateResponse(HttpStatusCode.OK, "True - User Does Exist! Did you mean to do a POST to create a new user?")); } return(Request.CreateResponse(HttpStatusCode.OK, "False - User Does Not Exist! Did you mean to do a POST to create a new user?")); } catch (Exception e) { return(Request.CreateResponse(HttpStatusCode.BadRequest, e.Message)); } }