public HttpResponseMessage CreateRole(CreateRoleModel model) { var responseMsg = this.ExceptionHandler( () => { var context = new AutoMorgueContext(); var roles = context.Roles; var role = roles.FirstOrDefault(r => r.Name == model.Name); if (role == null) { role = new Role { Name = model.Name }; } else { throw new Exception(); } context.Roles.Add(role); context.SaveChanges(); var response = this.Request.CreateResponse(HttpStatusCode.Created, role); return response; }); return responseMsg; }
public HttpResponseMessage RegisterUser(UserRegisterModel model) { var responseMsg = this.ExceptionHandler( () => { var context = new AutoMorgueContext(); UserDataPersister.ValidateUsername(model.Username); UserDataPersister.ValidateNickname(model.DisplayName); UserDataPersister.ValidateAuthCode(model.AuthCode); var usernameToLower = model.Username.ToLower(); var displayNameToLower = model.DisplayName.ToLower(); var users = context.Users; var user = users.FirstOrDefault(usr => usr.Username == usernameToLower || usr.DisplayName.ToLower() == displayNameToLower); var role = context.Roles.FirstOrDefault(r => r.Name == "user"); if (role == null) { role = new Role { Name = "user" }; } if (user != null) { throw new InvalidOperationException("Invalid Username or Password"); } var newUser = new User { Username = usernameToLower, DisplayName = model.DisplayName, AuthCode = model.AuthCode, Role = role }; var userInDb = context.Users.Add(newUser); context.SaveChanges(); userInDb.SessionKey = UserDataPersister.GenerateSessionKey(userInDb.Id); context.SaveChanges(); var loggedModel = new UserLoggedModel { DisplayName = userInDb.DisplayName, SessionKey = userInDb.SessionKey }; var response = this.Request.CreateResponse(HttpStatusCode.Created, loggedModel); response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = userInDb.Id })); return response; }); return responseMsg; }
public HttpResponseMessage ChangeRole(int userId, string role) { var responseMsg = this.ExceptionHandler( () => { var context = new AutoMorgueContext(); var users = context.Users; var user = users.FirstOrDefault(usr => usr.Id == userId); if (user == null) { throw new InvalidOperationException("Invalid Username or Password"); } var selectedRole = context.Roles.FirstOrDefault(r => r.Name == role); if (selectedRole == null) { selectedRole = new Role { Name = role }; context.Roles.Add(selectedRole); context.SaveChanges(); } user.Role = selectedRole; var response = this.Request.CreateResponse(HttpStatusCode.OK); return response; }); return responseMsg; }