public HttpResponseMessage LoginUser(UserModel model) { return this.ExecuteOperationAndHandleExceptions(() => { this.ValidateUser(model); var data = new UserRepository( ConfigurationManager.AppSettings["MongoConnectionString"], ConfigurationManager.AppSettings["Database"]); var dbUser = new DbUserModel() { Username = model.Username, AuthCode = model.AuthCode }; var user = data.GetLoggedUser(dbUser); if (user == null) { throw new FormatException("Invalid username or password"); } string token = null; if (user.AccessToken == null) { token = data.SetAccessToken(user, this.GenerateAccessToken(user.Id)); } else { token = user.AccessToken; } var responseModel = new LoginResponseModel() { Id = user.Id, Username = user.Username, AccessToken = token }; var response = this.Request.CreateResponse(HttpStatusCode.OK, responseModel); return response; }); }