public HttpResponseMessage LoginUser([FromBody] UserLoginModel model) { var responseMessage = this.PerformOperation(() => { using (var context = new BlogDbContext()) { this.ValidateUsername(model.Username); this.ValidateAuthCode(model.AuthCode); var user = context.Users.FirstOrDefault(m => m.Username == model.Username.ToLower()); if (user == null) { throw new ServerErrorException( "User does not exist", HttpStatusCode.BadRequest); } if (user.AuthCode != model.AuthCode) { throw new ServerErrorException( "Invalid authentication code", HttpStatusCode.Unauthorized); } if (user.SessionKey == null) { user.SessionKey = this.GenerateSessionKey(user.Id); context.SaveChanges(); } var loggedUserModel = new UserLoggedModel() { DisplayName = user.DisplayName, SessionKey = user.SessionKey }; var response = this.Request.CreateResponse( HttpStatusCode.Created, loggedUserModel); return response; } }); return responseMessage; }
public HttpResponseMessage RegisterUser([FromBody] UserRegisterModel model) { var responseMessage = this.PerformOperation(() => { using (var context = new BlogDbContext()) { if (model == null) { throw new ServerErrorException( "Username data must be set", HttpStatusCode.BadRequest); } this.ValidateUsername(model.Username); this.ValidateDisplayName(model.DisplayName); this.ValidateAuthCode(model.AuthCode); var modelUsernameLower = model.Username.ToLower(); var modelDisplayNameLower = model.DisplayName.ToLower(); var user = context.Users.FirstOrDefault(u => u.Username == modelUsernameLower || u.DisplayName.ToLower() == modelDisplayNameLower); if (user != null) { if (user.Username == modelUsernameLower) { throw new ServerErrorException( "Username already exists", HttpStatusCode.Conflict); } if (user.DisplayName.ToLower() == modelDisplayNameLower) { throw new ServerErrorException( "Display name already exists", HttpStatusCode.Conflict); } } var newUser = new User() { Username = modelUsernameLower, DisplayName = model.DisplayName, AuthCode = model.AuthCode }; context.Users.Add(newUser); context.SaveChanges(); newUser.SessionKey = GenerateSessionKey(newUser.Id); context.SaveChanges(); var loggedUserModel = new UserLoggedModel() { DisplayName = newUser.DisplayName, SessionKey = newUser.SessionKey }; var response = this.Request.CreateResponse( HttpStatusCode.Created, loggedUserModel); return response; } }); return responseMessage; }