public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var AppMember = new AppMember { UserName = model.Name, PhoneNumber = model.PhoneNumber, Email = model.Email, DateBirth = model.DateBirth, Address = model.Address, Active = true }; var result = await UserManager.CreateAsync(AppMember, model.Password); if (result.Succeeded) { // await SignInManager.SignInAsync(AppMember, isPersistent:false, rememberBrowser:false); // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link // string code = await UserManager.GenerateEmailConfirmationTokenAsync(AppMember.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = AppMember.Id, code = code }, protocol: Request.Url.Scheme); // await UserManager.SendEmailAsync(AppMember.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); //Add default User to Role Admin var result1 = UserManager.AddToRole(AppMember.Id, model.selectedRole); return(RedirectToAction("Pharmacists", "Admin")); } AddErrors(result); } // If we got this far, something failed, redisplay form ViewBag.Roles = await RetrieveRoles(); return(View(model)); }
public void Configuration(IAppBuilder app) { // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888 //app.CreatePerOwinContext(ApplicationDbContext.Create); app.CreatePerOwinContext <AppUserManager>(AppUserManager.Create); app.CreatePerOwinContext <AppRoleManager>(AppRoleManager.Create); app.CreatePerOwinContext <AppSignInManager>(AppSignInManager.Create); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login"), Provider = new CookieAuthenticationProvider { // Enables the application to validate the security stamp when the AppMember logs in. // This is a security feature which is used when you change a password or add an external login to your account. OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <AppUserManager, AppMember, int>( validateInterval: TimeSpan.FromMinutes(30), regenerateIdentityCallback: (manager, AppMember) => AppMember.GenerateUserIdentityAsync(manager), getUserIdCallback: (id) => (Int32.Parse(id.GetUserId()))) } }); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); // Enables the application to temporarily store AppMember information when they are verifying the second factor in the two-factor authentication process. app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5)); // Enables the application to remember the second login verification factor such as phone or email. // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from. // This is similar to the RememberMe option when you log in. app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie); }
public void Configuration(IAppBuilder app) { app.CreatePerOwinContext <AppUserManager>(AppUserManager.Create); app.CreatePerOwinContext <AppRoleManager>(AppRoleManager.Create); app.CreatePerOwinContext <AppSignInManager>(AppSignInManager.Create); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Auth/Login"), Provider = new CookieAuthenticationProvider { // Enables the application to validate the security stamp when the AppMember logs in. // This is a security feature which is used when you change a password or add an external login to your account. OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <AppUserManager, ExtendedUser, string>( validateInterval: TimeSpan.FromMinutes(30), regenerateIdentityCallback: (manager, AppMember) => AppMember.GenerateUserIdentityAsync(manager), getUserIdCallback: (id) => (id.GetUserId())) } }); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie }); }
private async Task SignInAsync(AppMember appMember, bool isPersistent) { AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.TwoFactorCookie); AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = isPersistent }, await appMember.GenerateUserIdentityAsync(UserManager)); }
public Task openTeam(User player) { var dbplayerfrak = Main.database.FractionCollection.AsQueryable() .FirstOrDefault(f => f.frakId == player.frakId); var frakmember = new List <AppMember>(); foreach (var member in dbplayerfrak.frakMember) { var dbMember = Main.database.CharacterCollection.AsQueryable() .FirstOrDefault(c => c.playerId == member.playerid); if (!dbMember.isOnline) { continue; } var newfrakmember = new AppMember { firstName = dbMember.firstName, lastName = dbMember.lastName, rank = member.rank }; frakmember.Add(newfrakmember); } if (dbplayerfrak != null) { var sortedList = frakmember.OrderByDescending(f => f.rank).ToList(); player.Emit("client:phone:openteamapp", JsonConvert.SerializeObject(sortedList)); return(Task.CompletedTask); } player.Emit("client:phone:openteamapp", "nofrak"); return(Task.CompletedTask); }
private async Task <AppMember> CreateExternalUser(string email, ExternalLoginInfo info) { var user = new AppMember { UserName = email, Email = email }; var result = await UserManager.CreateAsync(user); if (result.Succeeded) { AddRegisterActivity(user, info.Login.LoginProvider); result = await UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { return(await Task.FromResult(user)); } else { Logger.Trace("Create user failed: {0}", string.Join("; ", result.Errors)); AddErrors(result); } } else { Logger.Trace("Create user failed: {0}", string.Join("; ", result.Errors)); AddErrors(result); } return(await Task.FromResult <AppMember>(null)); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var AppMember = new AppMember { UserName = model.Email, Email = model.Email }; var result = await _userManager.CreateAsync(AppMember, model.Password); if (result.Succeeded) { await _signInManager.SignInAsync(AppMember, isPersistent : false, rememberBrowser : false); // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link // string code = await UserManager.GenerateEmailConfirmationTokenAsync(AppMember.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = AppMember.Id, code = code }, protocol: Request.Url.Scheme); // await UserManager.SendEmailAsync(AppMember.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); return(RedirectToAction("Index", "Home")); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new AppMember { UserName = model.Email, Email = model.Email, MemberType = 1 }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); // 如需如何進行帳戶確認及密碼重設的詳細資訊,請前往 https://go.microsoft.com/fwlink/?LinkID=320771 // 傳送包含此連結的電子郵件 // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // await UserManager.SendEmailAsync(user.Id, "確認您的帳戶", "請按一下此連結確認您的帳戶 <a href=\"" + callbackUrl + "\">這裏</a>"); return(RedirectToAction("Index", "Home")); } AddErrors(result); } // 如果執行到這裡,發生某項失敗,則重新顯示表單 return(View(model)); }
// 如需設定驗證的詳細資訊,請瀏覽 https://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { // 設定資料庫內容、使用者管理員和登入管理員,以針對每個要求使用單一執行個體 //app.CreatePerOwinContext(ApplicationDbContext.Create); app.CreatePerOwinContext(ApplicationDbContext.Create); app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create); app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create); //app.CreatePerOwinContext<AppUserManager>(AppUserManager.Create); //app.CreatePerOwinContext<AppRoleManager>(AppRoleManager.Create); // 讓應用程式使用 Cookie 儲存已登入使用者的資訊 // 並使用 Cookie 暫時儲存使用者利用協力廠商登入提供者登入的相關資訊; // 在 Cookie 中設定簽章 app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login"), Provider = new CookieAuthenticationProvider { // 讓應用程式在使用者登入時驗證安全性戳記。 // 這是您變更密碼或將外部登入新增至帳戶時所使用的安全性功能。 OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, AppMember, int>( validateInterval: TimeSpan.FromMinutes(30), regenerateIdentityCallback: (manager, AppMember) => AppMember.GenerateUserIdentityAsync(manager), getUserIdCallback: (id) => (Int32.Parse(id.GetUserId()))) } }); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); // 讓應用程式在雙因素驗證程序中驗證第二個因素時暫時儲存使用者資訊。 app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5)); // 讓應用程式記住第二個登入驗證因素 (例如電話或電子郵件)。 // 核取此選項之後,將會在用來登入的裝置上記住登入程序期間的第二個驗證步驟。 // 這類似於登入時的 RememberMe 選項。 app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie); // 註銷下列各行以啟用利用協力廠商登入提供者登入 //app.UseMicrosoftAccountAuthentication( // clientId: "", // clientSecret: ""); //app.UseTwitterAuthentication( // consumerKey: "", // consumerSecret: ""); //app.UseFacebookAuthentication( // appId: "", // appSecret: ""); //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions() //{ // ClientId = "", // ClientSecret = "" //}); }
private async Task AddLoginToUser(AppMember user, ExternalLoginInfo info) { if (!(await _userStore.GetLoginsAsync(user)).Any(x => info.Login.LoginProvider == x.LoginProvider && info.Login.ProviderKey == x.ProviderKey)) { AddAssignAccountActivity(user, info.Login.LoginProvider); await _userStore.AddLoginAsync(user, info.Login); } }
private async Task <string> GenerateLoginSuggestionMessage(AppMember user) { var availableLogins = await _userStore.GetLoginsAsync(user); if (!availableLogins.Any()) { return(""); } return(string.Format(Resources.Global.LoginUsingOneOf, availableLogins.Count > 1 ? Resources.Global.OneOf + " " : "", availableLogins.Select(x => x.LoginProvider).Aggregate((x1, x2) => $"{x1}, {x2}"))); }
public async Task <IdentityResult> RegisterUser(UserModel userModel) { AppMember user = new AppMember { UserName = userModel.UserName }; var result = await _userManager.CreateAsync(user, userModel.Password); return(result); }
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { // Configure the db context, AppMember manager and signin manager to use a single instance per request app.CreatePerOwinContext(ApplicationDbContext.Create); app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create); app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create); // Enable the application to use a cookie to store information for the signed in AppMember // and to use a cookie to temporarily store information about a AppMember logging in with a third party login provider // Configure the sign in cookie app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login"), Provider = new CookieAuthenticationProvider { // Enables the application to validate the security stamp when the AppMember logs in. // This is a security feature which is used when you change a password or add an external login to your account. OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, AppMember, int>( validateInterval: TimeSpan.FromMinutes(30), regenerateIdentityCallback: (manager, AppMember) => AppMember.GenerateUserIdentityAsync(manager), getUserIdCallback: (id) => (Int32.Parse(id.GetUserId()))) } }); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); // Enables the application to temporarily store AppMember information when they are verifying the second factor in the two-factor authentication process. app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5)); // Enables the application to remember the second login verification factor such as phone or email. // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from. // This is similar to the RememberMe option when you log in. app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie); // Uncomment the following lines to enable logging in with third party login providers //app.UseMicrosoftAccountAuthentication( // clientId: "", // clientSecret: ""); //app.UseTwitterAuthentication( // consumerKey: "", // consumerSecret: ""); //app.UseFacebookAuthentication( // appId: "", // appSecret: ""); //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions() //{ // ClientId = "", // ClientSecret = "" //}); }
public async Task <IHttpActionResult> RegisterExternal(RegisterExternalBindingModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var verifiedAccessToken = await VerifyExternalAccessToken(model.Provider, model.ExternalAccessToken); if (verifiedAccessToken == null) { return(BadRequest("Invalid Provider or External Access Token")); } AppMember user = await _repo.FindAsync(new UserLoginInfo(model.Provider, verifiedAccessToken.user_id)); bool hasRegistered = user != null; if (hasRegistered) { return(BadRequest("External user is already registered")); } user = new AppMember() { UserName = model.UserName }; IdentityResult result = await _repo.CreateAsync(user); if (!result.Succeeded) { return(GetErrorResult(result)); } var info = new ExternalLoginInfo() { DefaultUserName = model.UserName, Login = new UserLoginInfo(model.Provider, verifiedAccessToken.user_id) }; result = await _repo.AddLoginAsync(user.Id, info.Login); if (!result.Succeeded) { return(GetErrorResult(result)); } //generate access token response var accessTokenResponse = GenerateLocalAccessTokenResponse(model.UserName); return(Ok(accessTokenResponse)); }
public void createUserRolesAndDefaultUser() { ApplicationDbContext context = ApplicationDbContext.Create(); var roleManager = new RoleManager <IdentityRole, int>(new RoleStore <IdentityRole>(context)); var userManager = new UserManager <AppMember, int>(new UserStore <AppMember>(context)); // In Startup iam creating first Admin Role and creating a default Admin User if (!roleManager.RoleExists("Admin")) { // first we create Admin rool var role = new IdentityRole(); role.Name = "Admin"; var chkRole = roleManager.Create(role); if (chkRole.Succeeded) { //Here we create a Admin super user who will maintain the website var user = new AppMember(); user.UserName = "******"; user.Email = "*****@*****.**"; user.DateBirth = new DateTime(1994, 10, 31); user.Active = true; string user_password = "******"; var chkUser = userManager.Create(user, user_password); //Add default User to Role Admin if (chkUser.Succeeded) { var result1 = userManager.AddToRole(user.Id, "Admin"); } } } // creating Pharmacist role if (!roleManager.RoleExists("Pharmacist")) { var role = new IdentityRole(); role.Name = "Pharmacist"; roleManager.Create(role); } // creating Patient role if (!roleManager.RoleExists("Patient")) { var role = new IdentityRole(); role.Name = "Patient"; roleManager.Create(role); } }
private void AddUserActvity(AppMember user, string type, string details) { if (string.IsNullOrWhiteSpace(user?.Id)) { return; } _userActivityRepository.Insert(new UserActivity { AppId = RequestHelper.GetCurrentAppId() ?? Guid.Empty.ToString(), ServiceId = RequestHelper.GetCurrentServiceId() ?? Guid.Empty.ToString(), DateTime = DateTime.UtcNow, Type = type, UserId = user.Id, Details = details }); }
/// <summary> /// 获取ID数据 /// </summary> public List <AppMember> Getid() { HtmlDocument document = new HtmlDocument(); document.LoadHtml(srchtml); List <AppMember> tmplist = new List <AppMember>(); try { foreach (var badge in document.DocumentNode.SelectNodes("//div[@class=\"badge_row is_link\"]")) { var appIdNode = badge.SelectSingleNode(".//a[@class=\"badge_row_overlay\"]").Attributes["href"].Value; var appid = Regex.Match(appIdNode, @"gamecards/(\d+)/").Groups[1].Value; if (string.IsNullOrWhiteSpace(appid) || badlist.Contains(appid) || appIdNode.Contains("border=1")) { continue; } var hoursNode = badge.SelectSingleNode(".//div[@class=\"badge_title_stats_playtime\"]"); var hours = hoursNode == null ? string.Empty : Regex.Match(hoursNode.InnerText, @"[0-9\.,]+").Value; var nameNode = badge.SelectSingleNode(".//div[@class=\"badge_title\"]"); var name = WebUtility.HtmlDecode(nameNode.FirstChild.InnerText).Trim(); var cardNode = badge.SelectSingleNode(".//span[@class=\"progress_info_bold\"]"); var cards = cardNode == null ? string.Empty : Regex.Match(cardNode.InnerText, @"[0-9]+").Value; if (!string.IsNullOrWhiteSpace(cards)) { AppMember member = new AppMember(); member.Id = appid; member.Name = name; member.CardNum = cards; member.Time = hours == string.Empty ? "0" : hours; tmplist.Add(member); } } } catch { throw new Exception("源代码不正确"); } return(tmplist); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new AppMember { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { AddRegisterActivity(user, "Local"); // Comment the following line to prevent log in until the user is confirmed. await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); await UserManager.SendEmailAsync( user.Id, Resources.Global.ConfirmAccountTitle, Resources.Global.ConfirmAccountMessage.Replace("Url", callbackUrl)); var returnUrl = Request.QueryString["ReturnUrl"]; return(string.IsNullOrEmpty(returnUrl) ? RedirectToAction("Index", "Home") : RedirectToLocal(returnUrl)); } var message = $"Register failed: {string.Join("; ", result.Errors)}"; StackExchange.Exceptional.ErrorStore.LogException(new Exception(message), null); // avoid Name x is already taken. errors var identityResult = new IdentityResult(result.Errors.Where( x => !x.StartsWith(Resources.Global.Name + " ") && !x.Contains(" " + Resources.Global.Name + " "))); AddErrors(identityResult); // Show a hint about external providers ModelState.AddModelError("", Resources.Global.AlreadyRegisteredUsingXMessage .Replace("{LoginProviders}", WebConfigurationManager.AppSettings["AuthenticationProviders"] .ReplaceLast(",", " " + Resources.Global.Or + " "))); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <ActionResult> EditPharmacist(PharmacistViewModel model) { if (ModelState.IsValid) { var AppMember = new AppMember { UserName = model.Name, PhoneNumber = model.PhoneNumber, Email = model.Email, DateBirth = model.DateBirth, Address = model.Address, Active = model.Active, Id = model.Id }; var userStore = new UserStore <AppMember>(Context); await userStore.UpdateAsync(AppMember); return(RedirectToAction("Pharmacists", "Admin")); } // If we got this far, something failed, redisplay form return(View(model)); }
/// <summary> /// 获取ID数据 /// </summary> public List<AppMember> Getid() { HtmlDocument document = new HtmlDocument(); document.LoadHtml(srchtml); List<AppMember> tmplist = new List<AppMember>(); try { foreach (var badge in document.DocumentNode.SelectNodes("//div[@class=\"badge_row is_link\"]")) { var appIdNode = badge.SelectSingleNode(".//a[@class=\"badge_row_overlay\"]").Attributes["href"].Value; var appid = Regex.Match(appIdNode, @"gamecards/(\d+)/").Groups[1].Value; if (string.IsNullOrWhiteSpace(appid) || badlist.Contains(appid) || appIdNode.Contains("border=1")) { continue; } var hoursNode = badge.SelectSingleNode(".//div[@class=\"badge_title_stats_playtime\"]"); var hours = hoursNode == null ? string.Empty : Regex.Match(hoursNode.InnerText, @"[0-9\.,]+").Value; var nameNode = badge.SelectSingleNode(".//div[@class=\"badge_title\"]"); var name = WebUtility.HtmlDecode(nameNode.FirstChild.InnerText).Trim(); var cardNode = badge.SelectSingleNode(".//span[@class=\"progress_info_bold\"]"); var cards = cardNode == null ? string.Empty : Regex.Match(cardNode.InnerText, @"[0-9]+").Value; if (!string.IsNullOrWhiteSpace(cards)) { AppMember member = new AppMember(); member.Id = appid; member.Name = name; member.CardNum = cards; member.Time = hours == string.Empty ? "0" : hours; tmplist.Add(member); } } } catch { throw new Exception("源代码不正确"); } return tmplist; }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var allowedOrigin = context.OwinContext.Get <string>("as:clientAllowedOrigin"); if (allowedOrigin == null) { allowedOrigin = "*"; } context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin }); //using (AuthRepository _repo = new AuthRepository()) //{ AppMember user = await _repo.FindUser(context.UserName, context.Password); if (user == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } //} var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName)); identity.AddClaim(new Claim(ClaimTypes.Role, "user")); identity.AddClaim(new Claim("sub", context.UserName)); var props = new AuthenticationProperties(new Dictionary <string, string> { { "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId }, { "userName", context.UserName } }); var ticket = new AuthenticationTicket(identity, props); context.Validated(ticket); }
public async Task <ActionResult> EditProfile(ProfileViewModel model) { if (ModelState.IsValid) { var AppMember = new AppMember { UserName = model.Name, PhoneNumber = model.PhoneNumber, Email = model.Email, DateBirth = model.DateBirth, Address = model.Address, Active = true, Id = model.Id }; await UserManager.UpdateAsync(AppMember); return(RedirectToAction("Index", "Manage")); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return(RedirectToAction("Index", "Manage")); } if (ModelState.IsValid) { // Get the information about the AppMember from the external login provider var info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return(View("ExternalLoginFailure")); } var AppMember = new AppMember { UserName = model.Email, Email = model.Email }; var result = await _userManager.CreateAsync(AppMember); if (result.Succeeded) { result = await _userManager.AddLoginAsync(AppMember.Id, info.Login); if (result.Succeeded) { await _signInManager.SignInAsync(AppMember, isPersistent : false, rememberBrowser : false); return(RedirectToLocal(returnUrl)); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return(View(model)); }
public async Task <ActionResult> Register(RegisterViewModel model, bool captchaValid) { if (ModelState.IsValid && captchaValid) { var appMember = new AppMember { UserName = model.UserName, Email = model.Email }; var result = await UserManager.CreateAsync(appMember, model.Password); if (result.Succeeded) { await SendEmailConfirmationTokenAsync(appMember.Id, "Confirm your account"); ViewBag.Message = "Check your email and confirm your account, you must be confirmed " + "before you can log in."; return(View("Info")); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task CreateAsync(AuthenticationTokenCreateContext context) { var clientid = context.Ticket.Properties.Dictionary["as:client_id"]; if (string.IsNullOrEmpty(clientid)) { return; } var refreshTokenId = Guid.NewGuid().ToString("n"); var refreshTokenLifeTime = context.OwinContext.Get <string>("as:clientRefreshTokenLifeTime"); AppMember currentUser = await _repo.FindUserByUsername(context.Ticket.Identity.Name); var token = new RefreshToken() { Id = Helper.GetHash(refreshTokenId), ClientId = clientid, Subject = context.Ticket.Identity.Name, MemberId = currentUser.Id, IssuedUtc = DateTime.UtcNow, ExpiresUtc = DateTime.UtcNow.AddMinutes(Convert.ToDouble(refreshTokenLifeTime)) }; context.Ticket.Properties.IssuedUtc = token.IssuedUtc; context.Ticket.Properties.ExpiresUtc = token.ExpiresUtc; token.ProtectedTicket = context.SerializeTicket(); var result = await _repo.AddRefreshToken(token); if (result) { context.SetToken(refreshTokenId); } }
public SingleRun(AppMember app) { App = app; virtualcard = int.Parse(app.CardNum); }
public ActionResult Upload(HttpPostedFileBase upload) { string type = Request.Form["type"].ToString(); if (ModelState.IsValid) { if (upload != null && upload.ContentLength > 0) { var allowedExtensions = new[] { ".xlsx", ".csv" }; if (upload.FileName.EndsWith(".csv")) { Stream stream = upload.InputStream; StreamReader csvreader = new StreamReader(stream); csvreader.ReadLine(); // skip the headers : fisrt line while (!csvreader.EndOfStream) { var line = csvreader.ReadLine(); var values = line.Split(','); string PersonCode = values[0]; string PatientFirstName = values[1]; string PatientLastName = values[2]; string DOB = values[3]; string PatientZipCode = values[4]; string Phone = values[5]; string Email = values[6]; string DateFilled = values[7]; string PrescriptionNumber = values[8]; string DaysSupply = values[9]; string NumberOfRefills = values[10]; string NDCUPCHRI = values[11]; string GPIGenericName = values[12]; Email = PatientFirstName.ToLower() + "." + PatientLastName.ToLower() + "@ppok.com"; // email format: firstname.lastname string username = PatientFirstName + "." + PatientLastName; // username format: firstname.lastname if (DOB == "NULL") { DOB = "19760323"; } // just for now if (DateFilled == "NULL") { DateFilled = "19760323"; } // just for now //Thread.Sleep(10); // for testing if (UserManager.FindByEmail(Email) == null && username != ".") // skip duplicated users - at least for now { DateTime parsedDate; string[] formats = { "yyyyMMdd", "HHmmss" }; if (DateTime.TryParseExact(DOB, formats, null, DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.AdjustToUniversal, out parsedDate)) { // we have successfully parsed DOB to the date time // in this case, parsedDate will have the corresponding value } else { // unable to parse the DOB to date time parsedDate = new DateTime(); } /* step 01: create a user and save them to the database */ var appMember = new AppMember { UserName = username, PhoneNumber = Phone, Email = Email, DateBirth = parsedDate, Address = PatientZipCode, Active = true }; var result = UserManager.Create(appMember); if (result.Succeeded) { UserManager.AddToRole(appMember.Id, "Patient"); } /* step 02: create a medication record */ string med_id = NDCUPCHRI; string med_name = GPIGenericName; string med_description = "no-description"; MedicationDBManager medDB = new MedicationDBManager(); if (!medDB.exists(med_id)) // make sure the medication is in the db { Medication medication = new Medication(); medication.Id = med_id; medication.Med_Name = med_name; medication.Med_Description = med_description; medDB.create(medication); } /* step 03: create a perscription record, link to the previously created user and save it to the db */ int user_id = appMember.Id; int refills_left = Int32.Parse(NumberOfRefills); // TODO: need to deal with exceptions here int days_suply = Int32.Parse(DaysSupply); // TODO: need to deal with exceptions here DateTime parsedDateFilled; if (DateTime.TryParseExact(DateFilled, formats, null, DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.AdjustToUniversal, out parsedDateFilled)) { // we have successfully parsed DOB to the date time // in this case, parsedDate will have the corresponding value } else { // unable to parse the DateFilled to date time - just leave it null parsedDateFilled = new DateTime(); } Prescription prescription = new Prescription(); prescription.User_Id = user_id; prescription.Medication_Id = med_id; prescription.Refills_Left = refills_left; prescription.Days_Supply = days_suply; prescription.Last_Date_Filled = parsedDateFilled; PrescriptionDBManager prescDB = new PrescriptionDBManager(); int prescriptionID = prescDB.create(prescription); /* step 04: create a schedule record and save it to the db */ DateTime future_refill_date = new DateTime(); if (DateTime.Compare(parsedDateFilled, DateTime.Now) < 0) { future_refill_date = parsedDateFilled.AddDays(Int32.Parse(DaysSupply)); } else { future_refill_date = parsedDateFilled; } Schedule schedule = new Schedule(); schedule.Prescription_Id = prescriptionID; schedule.Future_Refill_Date = future_refill_date; schedule.Approved = false; ScheduleDBManager scheduleDBManager = new ScheduleDBManager(); scheduleDBManager.create(schedule); } } // save the import record //ImportDBManager importDBManager = new ImportDBManager(); //Import import = new Import { UserName = User.Identity.Name , FileName = upload.FileName, Type = type }; //importDBManager.addImport(import); TempData["previous_url"] = "~/home/Upload"; } else if (upload.FileName.EndsWith(".xlsx")) { TempData["CustomError"] = "This is a .xlsx file!"; } else { TempData["CustomError"] = "The file has to be a .csv file!"; } } else { TempData["CustomError"] = "You need to pload a file!"; } } return(RedirectToAction("Index")); }
public async Task <AppMember> FindAsync(UserLoginInfo loginInfo) { AppMember user = await _userManager.FindAsync(loginInfo); return(user); }
public async Task <IdentityResult> CreateAsync(AppMember user) { var result = await _userManager.CreateAsync(user); return(result); }
public async Task <AppMember> FindUser(string userName, string password) { AppMember user = await _userManager.FindAsync(userName, password); return(user); }
public async Task <AppMember> FindUserByUsername(string userName) { AppMember user = await _userManager.FindByNameAsync(userName); return(user); }