private IList <ProductDto> GetProductList(SSUser user) { ProductDto productDto = null; SSUser userJoin = null; return(UnitOfWork.CurrentSession.QueryOver <Product>() .JoinAlias(x => x.Owner, () => userJoin) .Where(x => x.Owner == user) .SelectList(u => u.Select(x => x.Name).WithAlias(() => productDto.Name)) .TransformUsing(Transformers.AliasToBean <ProductDto>()) .List <ProductDto>()); //var productList = UnitOfWork.CurrentSession.QueryOver<Product>() // .JoinAlias(x => x.Owner, () => userJoin) // .Where(() => userJoin == user) // .List<Product>(); // //var productListDto = new List<ProductDto>(); //foreach (var product in productList) //{ // productListDto.Add(new ProductDto // { // Name = product.Name // }); //} // // //return productListDto; }
public async Task <IActionResult> HandleExternalLogin() { ExternalLoginInfo info = await signInManager.GetExternalLoginInfoAsync(); var email = info.Principal.FindFirstValue(ClaimTypes.Email); var result = await signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent : false); if (!result.Succeeded) //user does not exist yet { var gUser = new SSUser { UserName = email, Email = email, EmailConfirmed = true }; var createResult = await userManager.CreateAsync(gUser); var roleResult = await userManager.AddToRoleAsync(gUser, "User"); await userManager.AddLoginAsync(gUser, info); var newUserClaims = info.Principal.Claims.Append(new Claim("userId", gUser.Id)); await userManager.AddClaimsAsync(gUser, newUserClaims); await signInManager.SignInAsync(gUser, isPersistent : true); } //Old process for generating JWT var user = await userManager.FindByNameAsync(email); var roles = await userManager.GetRolesAsync(user); //Step - 1 Creating Claims IdentityOptions identityOptions = new IdentityOptions(); var claims = new Claim[] { new Claim(identityOptions.ClaimsIdentity.UserIdClaimType, user.Id), new Claim(identityOptions.ClaimsIdentity.UserNameClaimType, user.UserName), new Claim(identityOptions.ClaimsIdentity.RoleClaimType, roles[0]) }; //Step - 2: Create signingKey from Secretkey var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("this-is-my-secret-key-for-angular8-app")); //Step -3: Create signingCredentials from signingKey with HMAC algorithm var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256); //Step - 4: Create JWT with signingCredentials, IdentityClaims & expire duration. var jwt = new JwtSecurityToken(signingCredentials: signingCredentials, expires: DateTime.Now.AddSeconds(30), claims: claims); //Step - 5: Finally write the token as response with OK(). //return Ok(new { tokenJwt = new JwtSecurityTokenHandler().WriteToken(jwt), userName = user.UserName, role = roles[0] }); var tokenJwt = new JwtSecurityTokenHandler().WriteToken(jwt); return(Redirect("http://Localhost:4200/google?tokenJwt=" + tokenJwt + "&id=" + user.Id + "&userName="******"&role=" + roles[0])); }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { returnUrl ??= Url.Content("~/"); ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); if (ModelState.IsValid) { var indexAtSign = Input.Email.IndexOf('@'); var emailSub = Input.Email.Substring(0, indexAtSign); //SS_ZaSa_zahidsafi956 var userName = "******" + Input.FirstName.Substring(0, 2) + Input.LastName.Substring(0, 2) + "_" + emailSub; var user = new SSUser { UserName = userName, Email = Input.Email }; var result = await _userManager.CreateAsync(user, Input.Password); if (result.Succeeded) { _logger.LogInformation("User created a new account with password."); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl }, protocol: Request.Scheme); await _emailSender.SendEmailAsync(Input.Email, "Confirm your email", $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>."); if (_userManager.Options.SignIn.RequireConfirmedAccount) { return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl })); } else { await _signInManager.SignInAsync(user, isPersistent : false); return(LocalRedirect(returnUrl)); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } // If we got this far, something failed, redisplay form return(Page()); }
public async Task <IActionResult> Register() { try { var model = JsonConvert.DeserializeObject <RegisterViewModel>(Request.Form["myModel"].ToString()); if (ModelState.IsValid) { var user = new SSUser() { UserName = model.UserName, Email = model.Email, DOB = model.DOB }; var userResult = await userManager.CreateAsync(user, model.Password); if (userResult.Succeeded) { var roleResult = await userManager.AddToRoleAsync(user, "User"); if (roleResult.Succeeded) { if (Request.Form.Files.Count > 0) { var filePath = Path.GetFullPath("~/ProfilePics/" + user.Id + ".jpeg").Replace("~\\", ""); using (var stream = new FileStream(filePath, FileMode.Create)) { Request.Form.Files[0].CopyTo(stream); } } return(Ok(user)); } } else { foreach (var item in userResult.Errors) { ModelState.AddModelError(item.Code, item.Description); } } } return(BadRequest(ModelState.Values)); } catch (Exception) { return(StatusCode(500, "Internal Server Error! Please Contact Admin!")); } }
public static void SSUsersSeeding(SSUsersRolesDB context, UserManager <SSUser> users) { // Creating the database if not created context.Database.EnsureCreated(); //Admin User SSUser userAdmin = new SSUser(); userAdmin.UserName = "******"; userAdmin.Email = "*****@*****.**"; userAdmin.EmailConfirmed = true; var admin = users.CreateAsync(userAdmin, "123ABC!@#def"); admin.Wait(); var resultAdmin = admin.Result; if (resultAdmin.Succeeded) { users.AddToRoleAsync(userAdmin, "Administrator").Wait(); } //Admin User 2 SSUser userAdmin2 = new SSUser(); userAdmin2.UserName = "******"; userAdmin2.Email = "*****@*****.**"; userAdmin2.EmailConfirmed = true; var admin2 = users.CreateAsync(userAdmin2, "123ABC!@#def"); admin2.Wait(); var resultAdmin2 = admin2.Result; if (resultAdmin2.Succeeded) { users.AddToRoleAsync(userAdmin2, "Administrator").Wait(); } // Teacher User // Student User }
public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); // Get the information about the user from the external login provider var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { ErrorMessage = "Error loading external login information during confirmation."; return(RedirectToPage("./Login", new { ReturnUrl = returnUrl })); } if (ModelState.IsValid) { var user = new SSUser { UserName = Input.Email, Email = Input.Email }; var result = await _userManager.CreateAsync(user); if (result.Succeeded) { result = await _userManager.AddLoginAsync(user, info); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent : false); _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider); return(LocalRedirect(returnUrl)); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } LoginProvider = info.LoginProvider; ReturnUrl = returnUrl; return(Page()); }
public void DummyData() { var user = new SSUser { Name = "Ali", BirthDate = DateTime.Now, ViewCount = 500 }; UnitOfWork.CurrentSession.SaveOrUpdate(user); var product = new Product { Name = "Ürün", Owner = user }; UnitOfWork.CurrentSession.SaveOrUpdate(product); using (var tran = UnitOfWork.CurrentSession.BeginTransaction()) { tran.Commit(); } }