public Authentication Login(LoginCredentials credentials) { var result = new Authentication(); var facebookCredentials = credentials as FacebookLoginCredentials; if (facebookCredentials != null) { var facebookSession = new Facebook.FacebookClient(facebookCredentials.AccessToken); dynamic me = facebookSession.Get("me"); var facebookUser = new FacebookUser { FacebookUserId = long.Parse(me["id"]), UserName = me["username"] }; result.UserId = _data.CheckOrInsertFacebookUser(facebookUser); var session = StartSession(result.UserId); result.Ticket = session.Key; result.ValidTill = session.Value; return result; } throw new NotImplementedException("Only facebook users are supported now"); }
public void LoginAsync(LoginCredentials credentials, Action<bool, string, Exception> callback) { try { var service = WcfRepository.GetService(); var domain = "SYMDEV"; var username = credentials.Username; var parts = credentials.Username.Split('\\'); if (parts.Length == 2) { domain = parts[0]; username = parts[1]; } service.ProxyValidateLoginCredentialsCompleted += (sender, args) => { if (args.Error == null) { callback(args.Result, args.authToken, null); } else { callback(false, null, args.Error); } }; service.ProxyValidateLoginCredentialsAsync(domain, username, credentials.Password, string.Empty); } catch (Exception ex) { callback(false, null, ex); } }
public void LoginAsync(LoginCredentials credentials, Action<bool, string, Exception> callback) { var worker = new BackgroundWorker(); worker.DoWork += (sender, e) => { System.Threading.Thread.Sleep(2000); }; worker.RunWorkerCompleted += (sender, e) => { callback(true, "blah", null); }; worker.RunWorkerAsync(); }
public HttpResponseMessage Login(LoginCredentials credentials) { Guid UserID = Guid.Empty; if (IsValid(credentials.EmailAddress, credentials.Password, out UserID)) { var claims = new List<Claim>() { new Claim(ClaimTypes.Name, UserID.ToString()) }; var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie); Authentication.SignIn(new AuthenticationProperties() { IsPersistent = false }, identity); return Request.CreateResponse(HttpStatusCode.OK, UserID); } else { return Request.CreateResponse(HttpStatusCode.Unauthorized); } }
public HttpResponseMessage Post(LoginCredentials credentials) { string error = null; var user = Repository<User>.Select(u => u.UserName, credentials.Username); if (user == null) error = "Invalid user name"; else if (user.Password != credentials.Password) error = "Invalid password"; return Request.CreateResponse(HttpStatusCode.OK, new LoginResponse { ErrorMessage = error, Success = String.IsNullOrEmpty(error), User = String.IsNullOrEmpty(error) ? user : null }); }
private Optional <ProtectedLoginCredentials> ProtectCredentials(LoginCredentials loginCredentials) { try { var usrBytes = Encoding.UTF8.GetBytes(loginCredentials.Username); var psdBytes = Encoding.UTF8.GetBytes(loginCredentials.Password); return(new ProtectedLoginCredentials { ProtectedUsername = Convert.ToBase64String(ProtectedData.Protect(usrBytes, Entropy, DataProtectionScope.LocalMachine)), ProtectedPassword = Convert.ToBase64String(ProtectedData.Protect(psdBytes, Entropy, DataProtectionScope.LocalMachine)), CharacterName = loginCredentials.CharacterName, Default = loginCredentials.Default }); } catch { return(Optional.None <ProtectedLoginCredentials>()); } }
public JsonDocument Register([FromBody] Registration user) { var users = new PKG_USERS(); var register = users.Register(user.email, user.password, user.fullName, user.phone, user.tin, user.samformaType, user.userType); if (register) { var email = new EmailService(); email.SendEmail(user.email, "რეგისტრაცია {{საიტი}} ზე", "თქვენ წარმატებით დარეგისტრირდით {{საიტი}} პორტალზე."); LoginCredentials login = new LoginCredentials(); login.email = user.email; login.password = user.password; return(this.Authenticate(login)); } else { return(throwError("ელ.ფოსტა უკვე რეგისტრირებულია.")); } }
public async Task <IActionResult> Authenticate([Required] LoginCredentials credentials) { if (!ModelState.IsValid) { return(BadRequest()); } if (!await _userService.ValidateCredentials(credentials)) { return(Unauthorized(new ErrorResponse() { Errors = new[] { "Invalid username or password" } })); } var jwt = await _tokenService.GetTokenFromLoginCredentialsAsync(credentials.UserName, credentials.Password); return(new JsonResult(jwt)); }
public CustomUser SetSecQuestion(string oktaId, string secQuestion, string secQuestionAnswer) { User oktaUser = new User(); User rspOktaUser = new User(); LoginCredentials myLoginCredentials = new LoginCredentials(); myLoginCredentials.RecoveryQuestion.Question = secQuestion; myLoginCredentials.RecoveryQuestion.Answer = secQuestionAnswer; oktaUser.Id = oktaId; rspOktaUser = _usersClient.SetCredentials(oktaUser, myLoginCredentials); CustomUser customUser = new CustomUser(oktaUser); _logger.Debug("set credentials for " + rspOktaUser.Profile.Login); return(customUser); }
public void CredsFromConfigTest() { ClientConfig config = new ClientConfig { CompanyId = "testcompany", UserId = "testuser", UserPassword = "******" }; LoginCredentials loginCreds = new LoginCredentials(config, this.SenderCreds); Assert.Equal("testcompany", loginCreds.CompanyId); Assert.Equal("testuser", loginCreds.UserId); Assert.Equal("testpass", loginCreds.Password); Endpoint endpoint = loginCreds.SenderCredentials.Endpoint; Assert.Equal("https://api.intacct.com/ia/xml/xmlgw.phtml", endpoint.ToString()); Assert.IsType <SenderCredentials>(loginCreds.SenderCredentials); }
public async Task <IActionResult> Login([FromBody] LoginCredentials credentials) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (!await _userRepository.IsValidUser(credentials.Email)) { return(BadRequest("Invalid email")); } var now = DateTime.UtcNow; var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, credentials.Email), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.Iat, new DateTimeOffset(now) .ToUniversalTime() .ToUnixTimeSeconds() .ToString(), ClaimValueTypes.Integer64), }; var signingCredentials = new SigningCredentials(_authSettings.TokenSigningKey, SecurityAlgorithms.HmacSha256); var expiration = now.AddDays(1); var jwt = new JwtSecurityToken( issuer: "PV247 API", audience: "PV247 Students", claims: claims, notBefore: now, expires: expiration, signingCredentials: signingCredentials); var encodedJwt = new JwtSecurityTokenHandler() .WriteToken(jwt); return(Ok(new LoginResponse { Token = encodedJwt, Expiration = expiration })); }
public string Login(LoginCredentials credentials) { UserAccount userAccount = _accountWrapper.Repository.GetMatching(account => account.Credentials.Email == credentials.Email && account.Credentials.Password == credentials.Password ).FirstOrDefault(); if (userAccount != default) { if (!userAccount.IsActivated) { throw new BadRequestException("Account not activated."); } return(_jwtManager.Encode(MapAccountToUserToken(userAccount))); } return(null); }
public User CreateUser(UserDto dto) { if (!ValidUserDto(dto)) { return(null); } if (!PasswordFollowsGuidelines(dto.Password)) { return(null); } if (UsernameExists(dto.Username)) { return(null); } var userRole = _context.Roles.Where(x => x.Title == "User").FirstOrDefault(); User U = new User() { FirstName = dto.FirstName, LastName = dto.LastName, Email = dto.Email, Role = userRole, RoleId = userRole.Id }; LoginCredentials lc = new LoginCredentials(); _context.Users.Add(U); _context.SaveChanges(); lc.UserId = U.UserId; lc.Username = dto.Username; string hash = _hasher.CreateHash(dto.Password); lc.PasswordHash = hash; _context.LoginCredentials.Add(lc); _context.SaveChanges(); return(U); }
public ActionResult ChangePassword(Guid id, CustodianLoginModel custodianLogin) { var custodian = _custodiansQuery.GetCustodian(id); if (custodian == null) { return(NotFound("custodian", "id", id)); } var credentials = _loginCredentialsQuery.GetCredentials(custodian.Id); if (credentials == null) { return(NotFound("custodian", "id", id)); } try { // Validate. custodianLogin.Validate(); // Update. credentials.PasswordHash = LoginCredentials.HashToString(custodianLogin.Password); _loginCredentialsCommand.UpdateCredentials(custodian.Id, credentials, User.Id().Value); const string message = "The password has been reset."; return(RedirectToRouteWithConfirmation(CustodiansRoutes.Edit, new { id }, message)); } catch (UserException ex) { ModelState.AddModelError(ex, new StandardErrorHandler()); } custodianLogin.LoginId = credentials.LoginId; return(View("Edit", new CustodianUserModel { User = _custodiansQuery.GetCustodian(id), UserLogin = custodianLogin, Community = _communitiesQuery.GetCommunity(custodian.AffiliateId.Value), })); }
public void AttemptLogin_returns_failure_result_when_user_is_not_found([Frozen] CSF.Security.Authentication.IPasswordAuthenticationService authService, LoginLogoutManager sut, ILoginRequest request, LoginCredentials credentials) { // Arrange Mock.Get(request) .Setup(x => x.GetCredentials()) .Returns(credentials); Mock.Get(authService) .Setup(x => x.Authenticate(credentials)) .Returns(AuthenticationResult.UserNotFound); // Act var result = sut.AttemptLogin(request); // Assert Assert.IsFalse(result.Success); }
public ActionResult AddTeam(string MgrId) { LoginCredentials LG = new LoginCredentials(); LG.swg = System.Web.HttpContext.Current.Session["swgId"] as String; System.Web.HttpContext.Current.Session["role"] = LoginController.role(); if (System.Web.HttpContext.Current.Session["role"].ToString() == "null") { return(Content("Not Authorized User")); } DBManager db = new DBManager(); ViewBag.MgrId = MgrId; ViewBag.JobList = db.JobTitles(); ViewBag.ProductList = db.ProductNames(); ViewBag.DeptList = db.DeptNames(); ViewBag.IsSubmitted = false; return(View()); }
public IActionResult Login([FromBody] LoginCredentials credentials) { var user = Users.FirstOrDefault(x => x.Email == credentials.Email); if (user != null) { if (user.Password.Equals(credentials.Password)) { var claims = new List <Claim> { new Claim("Email", user.Email), new Claim("Id", user.Id.ToString()), new Claim("Role", user.Role.Name.ToString()) }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AuthOptions.SIGNING_KEY)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: "https://localhost:44385/", audience: "https://localhost:44385/", claims: claims, expires: DateTime.Now.AddDays(1), signingCredentials: creds); var encodedToken = new JwtSecurityTokenHandler().WriteToken(token); Request.HttpContext.Response.Headers.Add("Authorization", "Bearer " + encodedToken); var responce = new { token = encodedToken, id = user.Id, firstname = user.FirstName, lastname = user.LastName, role = user.Role.Name.ToString() }; return(Json(responce)); } return(BadRequest("Wrong email or password")); } return(BadRequest("Could not create token")); }
public ActionResult ChangePassword(Guid id, AdministratorLoginModel administratorLogin) { var administrator = _administratorsQuery.GetAdministrator(id); if (administrator == null) { return(NotFound("administrator", "id", id)); } var credentials = _loginCredentialsQuery.GetCredentials(id); if (credentials == null) { return(NotFound("administrator", "id", id)); } try { // Validate. administratorLogin.Validate(); // Update. credentials.PasswordHash = LoginCredentials.HashToString(administratorLogin.Password); _loginCredentialsCommand.UpdateCredentials(administrator.Id, credentials, User.Id().Value); const string message = "The password has been reset."; return(RedirectToRouteWithConfirmation(AdministratorsRoutes.Edit, new { id }, message)); } catch (UserException ex) { ModelState.AddModelError(ex, new StandardErrorHandler()); } administratorLogin.LoginId = credentials.LoginId; return(View("Edit", new UserModel <Administrator, AdministratorLoginModel> { User = _administratorsQuery.GetAdministrator(id), UserLogin = administratorLogin, })); }
public void AttemptLogin_returns_failure_result_when_authentication_fails([Frozen] CSF.Security.Authentication.IPasswordAuthenticationService authService, LoginLogoutManager sut, ILoginRequest request, LoginCredentials credentials, [HasIdentity] User user) { // Arrange Mock.Get(request) .Setup(x => x.GetCredentials()) .Returns(credentials); Mock.Get(authService) .Setup(x => x.Authenticate(credentials)) .Returns(new AuthenticationResult(user.GetIdentity(), user.Username, false)); // Act var result = sut.AttemptLogin(request); // Assert Assert.IsFalse(result.Success); }
public ActionResult Index(FormCollection T) { LoginCredentials login = new LoginCredentials(T); if (login.IsDesignationNullOrEmpty()) { System.Threading.Thread.Sleep(3000); return(View()); } if (login.IsManager()) { return(RedirectToAction("Index", "MyTeam")); } else { return(RedirectToAction("HRRequest", "DisplayHRRequests")); } }
public void TestCreateUser() { // Create a member account. const string userId = "*****@*****.**"; _memberAccountsCommand.CreateTestMember(userId, false); // Authenticate the user, who is deactivated when first created. var credentials = new LoginCredentials { LoginId = userId, PasswordHash = LoginCredentials.HashToString("password") }; Assert.AreEqual(AuthenticationStatus.Deactivated, _loginAuthenticationCommand.AuthenticateUser(credentials).Status); var profile = _membersQuery.GetMember(userId); Assert.IsNotNull(profile); }
async Task CreateOrLoginUser(string url) { UserName = UserNameTextBox.Text; Password = PasswordTextBox.Password; var reqVal = new LoginCredentials() { name = UserName, password = Password }; var loginRoot = await Request.PostAsync <LoginRoot>(url, JsonConvert.SerializeObject(reqVal)); if (loginRoot.status.success == true && !string.IsNullOrEmpty(loginRoot.token)) { Frame.Navigate(typeof(MainPage)); } else { new Dialog().ShowText(loginRoot.status.reason); } }
public async Task <IActionResult> Login([FromBody] LoginCredentials credentials) { var identity = await _userManager.FindByNameAsync(credentials.UserName); if (identity == null) { return(NotFound()); } if (!await _userManager.CheckPasswordAsync(identity, credentials.Password)) { return(BadRequest("Wrong credentials")); } var jwt = _jwtFactory.GenerateJwt(identity, credentials.UserName, identity.EmployeeRole, new JsonSerializerSettings { Formatting = Formatting.Indented }); return(Ok(jwt)); }
// // GET: /Login/ public ActionResult LoginError(FormCollection T) { //System.Threading.Thread.Sleep(3000); LoginCredentials login = new LoginCredentials(T); if (login.IsDesignationNullOrEmpty()) { return(PartialView("LoginError", login)); } if (login.IsManager()) { return(Json(new { url = Url.Action("Index", "MyTeam") })); //return RedirectToAction("Index", "MyTeam"); } else { return(Json(new { url = Url.Action("HRRequest", "DisplayHRRequests") })); //return RedirectToAction("HRRequest", "DisplayHRRequests"); } }
protected void RegisterButton_Click(object sender, EventArgs e) { if (AccountName.Text == "" || Password.Text == "" || Email.Text == "") { Response.Write("<script>alert('A field was left blank. Please try again.');</script>"); } else { LoginCredentials registeringAccount = new LoginCredentials(AccountName.Text, Password.Text, Email.Text); if (registeringAccount.Register()) { //good for you Response.Redirect(@"~/Default.aspx"); } else { Response.Write("<script>alert('Account name or e-mail already in use.');</script>"); } } }
public static Boolean Register(LoginCredentials loginCredentials) { // get the bytes to store from the credentials byte[] bytes = loginCredentials.GetBytes(); // base64 of the username string username = loginCredentials.Username; // read through the bytes to see if username exists byte[] rawBytes = ReadStoredBytes(); if (rawBytes is null) { return(false); } for (int i = 0; i < rawBytes.Length / 288; i++) { int lowerIndex = 288 * i; byte[] user = rawBytes[lowerIndex..(lowerIndex + 288)];
public void CredsFromEnvironmentWithEntityTest() { Environment.SetEnvironmentVariable("INTACCT_COMPANY_ID", "envcompany"); Environment.SetEnvironmentVariable("INTACCT_ENTITY_ID", "enventity"); Environment.SetEnvironmentVariable("INTACCT_USER_ID", "envuser"); Environment.SetEnvironmentVariable("INTACCT_USER_PASSWORD", "envuserpass"); ClientConfig config = new ClientConfig(); LoginCredentials loginCreds = new LoginCredentials(config, this.SenderCreds); Assert.Equal("envcompany", loginCreds.CompanyId); Assert.Equal("enventity", loginCreds.EntityId); Assert.Equal("envuser", loginCreds.UserId); Assert.Equal("envuserpass", loginCreds.Password); Environment.SetEnvironmentVariable("INTACCT_COMPANY_ID", null); Environment.SetEnvironmentVariable("INTACCT_ENTITY_ID", null); Environment.SetEnvironmentVariable("INTACCT_USER_ID", null); Environment.SetEnvironmentVariable("INTACCT_USER_PASSWORD", null); }
public IActionResult Login(LoginCredentials credentials) { string authToken; try { authToken = _credentialsService.Login(credentials); } catch (BadRequestException e) { return(BadRequest(e.Message)); } if (authToken != default) { AttackAuthTokenToResponse(HttpContext.Response, authToken); return(Ok()); } return(BadRequest("Failed to login.")); }
public async Task <IActionResult> LogUser([FromBody] LoginCredentials credentials) { EntityEntry <User> loggedUser; try { var authenticatedUser = await _magento.AuthenticateUser(new Models.User { Email = credentials.Email, Password = credentials.Password }); if (authenticatedUser.Token == null) { return(NoContent()); } var user = await _dbContext.Users.FirstOrDefaultAsync(x => x.Email == credentials.Email); if (user == null) { loggedUser = await _dbContext.Users.AddAsync(authenticatedUser); } else { user.Name = authenticatedUser.Name; user.LastName = authenticatedUser.LastName; user.Token = authenticatedUser.Token; user.Cpf = authenticatedUser.Cpf; user.Email = authenticatedUser.Email; loggedUser = _dbContext.Users.Update(user); } await _dbContext.SaveChangesAsync(); return(Ok(loggedUser.Entity)); } catch (Exception) { return(StatusCode((int)HttpStatusCode.InternalServerError)); } }
public IActionResult Login([FromBody] LoginCredentials dt) { if (dt?.emailAddress == null || dt.password == null) { return(BadRequest()); } Client clientFound = _clientService.GetClientByMailAndPasswordMatch(dt.emailAddress, dt.password); Provider providerFound = null; if (clientFound == null) { providerFound = _providerService.GetProviderByPasswordAndMailMatch(dt.emailAddress, dt.password); } if ((clientFound == null) && (providerFound == null)) { return(StatusCode(401)); } string token = ""; if (clientFound != null) { token = _tokenManager.GenerateToken(new TokenData() { UserId = clientFound.Id, Username = clientFound.EmailAddress, Role = clientFound.Role.RoleName }); } if (providerFound != null) { token = _tokenManager.GenerateToken(new TokenData() { UserId = providerFound.Id, Username = providerFound.EmailAddress, Role = "Provider" }); } return(Ok(new { token })); }
public ActionResult NewHire(FormCollection frm) { ViewBag.MgrId = System.Web.HttpContext.Current.Session["swgId"] as String; LoginCredentials LG = new LoginCredentials(); LG.swg = System.Web.HttpContext.Current.Session["swgId"] as String; RequestData c = new RequestData(); if (ModelState.IsValid) { c.JobId = int.Parse(frm["JobId"]); c.DeptId = int.Parse(frm["DeptId"]); c.ProductId = int.Parse(frm["ProductId"]); c.criticality = int.Parse(frm["criticality"]); c.EstimatedCTC = 50000; c.minEstimatedCTC = 150000; c.EssentialSkillIds = frm["EssentialIdsSelectedList"].Split(',').Select(int.Parse).ToList(); c.DesiredSkillIds = frm["DesiredIdsSelectedList"].Split(',').Select(int.Parse).ToList(); c.OptionalSkillIds = frm["OptionalIdsSelectedList"].Split(',').Select(int.Parse).ToList(); c.CreatedByEmpId = System.Web.HttpContext.Current.Session["swgId"] as String; c.vacancies = int.Parse(frm["vacancies"]); c.mineducation = frm["mineducation"]; c.minexperience = int.Parse(frm["minexperience"]); c.InputComments = frm["InputComments"]; c.ReqType = "New Hire"; c.CreatedDate = DateTime.Now; c.LastModifiedDate = DateTime.Now; int ReqId = BusinessComponents.Request.CreateNewRequest(c); ViewBag.reqID = ReqId; ViewBag.JobList = BusinessComponents.Request.JobTitles(); ViewBag.ProductList = BusinessComponents.Request.ProductNames(); ViewBag.DeptList = BusinessComponents.Request.DeptNames(); ViewBag.SkillsList = BusinessComponents.Request.Skills(); ViewBag.IsSubmitted = true; return(RedirectToAction("Index", "DisplayRequest", c.CreatedByEmpId)); } return(RedirectToAction("NewHire", LG)); }
private byte[] Login(byte[] data, out long size) { LoginCredentials creds = data.DeserializeObject <LoginCredentials>(out size); LoginResponse response = new LoginResponse() { error = LoginError.LOGIN_SUCCESS, sessionId = 0 }; for (int i = 0; i < clients.Count; i++) { if (clients[i].Passwd == creds.passwd && clients[i].Id == creds.login) { foreach (var check in connectedClients) { if (check.Value.Id == i) { response.error = LoginError.LOGIN_ALREADYLOGIN; break; } } if (response.error != LoginError.LOGIN_ALREADYLOGIN) { do { response.sessionId = randDevice.Next(); }while (response.sessionId == 0); connectedClients.Add(response.sessionId, new ConnectedClient(i)); } break; } } // nothing was found if (response.sessionId == 0) { response.error = LoginError.LOGIN_INVALIDPASSWD; } return(CreateMessage(ServerProtocol.svc_login, response.SerializeToByteArray())); }
private void CreateAdministrator(CreateAdministratorModel model) { var administrator = new Administrator { EmailAddress = new EmailAddress { Address = model.EmailAddress, IsVerified = true }, FirstName = model.FirstName, LastName = model.LastName, }; var credentials = new LoginCredentials { LoginId = model.LoginId, PasswordHash = LoginCredentials.HashToString(model.Password), }; // Create the account. _administratorAccountsCommand.CreateAdministrator(administrator, credentials); }
public async Task <IActionResult> Login([FromBody] LoginCredentials loginCredentials) { var account = await _DataBaseContext.Accounts.Include(x => x.Password).Include(x => x.TokensChain).SingleOrDefaultAsync(x => x.Email == loginCredentials.Email); if (account == null) { return(new JsonResult(new ServerResponse <object>(new ServerError(ServerError.UserNotFound)))); } var validAccount = account?.Password.ComparePassword(loginCredentials.Password); if (validAccount.HasValue && validAccount.Value) { account.RetreiveToken(); _DataBaseContext.Accounts.Update(account); await _DataBaseContext.SaveChangesAsync(); var response = new ServerResponse <TokenResult>(account.GetTokens()); return(new JsonResult(response)); } return(new JsonResult(new ServerResponse <object>(new ServerError(ServerError.InvalidPassword)))); }
public bool LogIn(LoginCredentials loginCredentials) { using (var db = new s18838Context()) { var salt = GetSalt(loginCredentials.Login); var valueBytes = KeyDerivation.Pbkdf2( loginCredentials.Password, Encoding.UTF8.GetBytes(salt), KeyDerivationPrf.HMACSHA512, 1000, 256 / 8 ); var password = Convert.ToBase64String(valueBytes); return(db.Student .Where(s => s.IndexNumber == loginCredentials.Login && s.Password == password) .Select(e => true) .SingleOrDefault()); } }
private void configureDBCredentials(string username, string password) { _lastDBCredentials = new LoginCredentials(username, password); configureDBCredentials(); }
public HttpResponseMessage PostLogin(LoginCredentials login) { //if (!ModelState.IsValid) //{ // // throw error (ivalidateable object) // // throw httpresponse exce. // // webdev blog // // webapi pipeline // // tracing system? nuget webapi system diagnostics trace // // attribute routing.org //} var loginReturnStatus = new LoginReturnStatus(); HttpResponseMessage response; if (!String.IsNullOrEmpty(login.Username) && !String.IsNullOrEmpty(login.Password)) { var loginSuccess = Membership.ValidateUser(login.Username, login.Password); if (loginSuccess) { FormsAuthentication.SetAuthCookie(login.Username, login.RememberMe); AttendeesResult attendeesResultFull = AttendeesManager.I.Get(new AttendeesQuery() { CodeCampYearId = Utils.CurrentCodeCampYear, IncludeAttendeesCodeCampYearResult = true, Username = login.Username }).FirstOrDefault(); if (attendeesResultFull != null) { response = Request.CreateResponse(HttpStatusCode.OK, MakeSafeAttendee(attendeesResultFull)); } else { response = Request.CreateErrorResponse(HttpStatusCode.Forbidden, "User Authenticated, but no user record in database found."); } } else { response = Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Username and Password are not valid. Please Try again"); } } else { response = Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Username and Password must both have values"); loginReturnStatus.Status = "Failed"; loginReturnStatus.Message = "Username and Password must both have values"; } return response; }
public HttpResponseMessage PostIsLoggedIn(LoginCredentials login) { var loginReturnStatus = new LoginReturnStatus(); HttpResponseMessage response; if (User.Identity.IsAuthenticated) { AttendeesResult attendeesResultFull = AttendeesManager.I.Get(new AttendeesQuery { Username = User.Identity.Name, CodeCampYearId = Utils.CurrentCodeCampYear, IncludeAttendeesCodeCampYearResult = true }).FirstOrDefault(); if (attendeesResultFull != null) { //var attendeesResult = AttendeesResultStripped(attendeesResultFull); loginReturnStatus.Data = attendeesResultFull; response = Request.CreateResponse(HttpStatusCode.OK, MakeSafeAttendee(attendeesResultFull)); } else { response = Request.CreateErrorResponse(HttpStatusCode.Forbidden, "User Authenticated, but no user record in database found."); } } else { response = Request.CreateErrorResponse(HttpStatusCode.Forbidden, "User Not Authenticated To Server"); loginReturnStatus.Status = "Failed"; loginReturnStatus.Message = "Not Authenticated"; } return response; }
public Authentication Login(LoginCredentials credentials) { using (var business = new SocialServiceBusiness()) return business.Authentication.Login(credentials); }
public HttpResponseMessage PostLogOut(LoginCredentials login) { if (User.Identity.IsAuthenticated) { FormsAuthentication.SignOut(); } return Request.CreateResponse(HttpStatusCode.OK, ""); }