private void CreateAdminRoleAndUser(MundialitoContext context) { var UserManager = new UserManager <MundialitoUser>(new UserStore <MundialitoUser>(context)); var RoleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context)); //Create Role Admin if it does not exist string name = "Admin"; if (!RoleManager.RoleExists(name)) { var roleresult = RoleManager.Create(new IdentityRole(name)); } //Create Admin user with password=123456 var user = new MundialitoUser(); user.UserName = WebConfigurationManager.AppSettings["AdminUserName"]; user.FirstName = WebConfigurationManager.AppSettings["AdminFirstName"]; user.LastName = WebConfigurationManager.AppSettings["AdminLastName"]; user.Email = WebConfigurationManager.AppSettings["AdminEmail"]; var adminresult = UserManager.Create(user, "123456"); //Add User Admin to Role Admin if (adminresult.Succeeded) { var result = UserManager.AddToRole(user.Id, name); } }
public async Task <IHttpActionResult> Register(RegisterBindingModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (TournamentTimesUtils.GeneralBetsCloseTime < DateTime.UtcNow) { return(BadRequest("Tournament is not closed for registration")); } if (!PrivateKeyValidator.ValidatePrivateKey(model.PrivateKey, model.Email)) { return(BadRequest("Invalid private key")); } MundialitoUser user = new MundialitoUser { UserName = model.UserName, Email = model.Email, LastName = model.LastName, FirstName = model.FirstName }; IdentityResult result = await UserManager.CreateAsync(user, model.Password); IHttpActionResult errorResult = GetErrorResult(result); if (errorResult != null) { return(errorResult); } return(Ok()); }
private void SendBetMail(Bet bet) { try { MundialitoUser user = userManager.FindById(userProivider.UserId); Game game = gamesRepository.GetGame(bet.GameId); string sendGridUsername = ConfigurationManager.AppSettings["SendGridUserName"]; string sendGridPassword = ConfigurationManager.AppSettings["SendGridPassword"]; string linkAddress = ConfigurationManager.AppSettings["LinkAddress"]; string fromAddress = ConfigurationManager.AppSettings["fromAddress"]; MailMessage message = new MailMessage(); message.To.Add(new MailAddress(user.Email, user.FirstName + " " + user.LastName)); message.From = new MailAddress(fromAddress, ConfigurationManager.AppSettings["ApplicationName"]); message.Subject = string.Format("{0} Bet Update: You placed a bet on {1} - {2}", ConfigurationManager.AppSettings["ApplicationName"], game.HomeTeam.Name, game.AwayTeam.Name); StringBuilder builder = new StringBuilder(); builder.AppendLine(string.Format("Result: {0} {1} - {2} {3}", game.HomeTeam.Name, bet.HomeScore, game.AwayTeam.Name, bet.AwayScore)); builder.AppendLine(string.Format("Corners: {0}", bet.CornersMark)); builder.AppendLine(string.Format("Yellow Cards: {0}", bet.CardsMark)); message.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(builder.ToString(), (Encoding)null, "text/plain")); SmtpClient smtpClient = new SmtpClient("smtp.sendgrid.net", Convert.ToInt32(587)); NetworkCredential networkCredential = new NetworkCredential(sendGridUsername, sendGridPassword); smtpClient.Credentials = (ICredentialsByHost)networkCredential; smtpClient.Send(message); } catch (Exception ex) { Trace.TraceError("Exception during mail sending. Exception: {0}", ex.Message); } }
private static void SendNotification(MundialitoUser user, Game game, TextWriter log) { try { string sendGridUsername = ConfigurationManager.AppSettings["SendGridUserName"]; string sendGridPassword = ConfigurationManager.AppSettings["SendGridPassword"]; string linkAddress = ConfigurationManager.AppSettings["LinkAddress"]; string fromAddress = ConfigurationManager.AppSettings["fromAddress"]; MailMessage message = new MailMessage(); message.To.Add(new MailAddress(user.Email, user.FirstName + " " + user.LastName)); message.From = new MailAddress(fromAddress, ConfigurationManager.AppSettings["ApplicationName"]); TimeSpan timeSpan = game.CloseTime - DateTime.UtcNow; message.Subject = string.Format("WARNING: The game between {0} and {1}, will be closed in {2} minutes and you havn't placed a bet yet", (object)game.HomeTeam.Name, (object)game.AwayTeam.Name, (object)(int)timeSpan.TotalMinutes); string content1 = string.Format("Please submit your bet as soon as possible"); string content2 = "<p>Please submit your bet as soon as possible. <a href='" + linkAddress + "'>Click here for the Bets Center</a></p>"; message.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(content1, (Encoding)null, "text/plain")); message.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(content2, (Encoding)null, "text/html")); SmtpClient smtpClient = new SmtpClient("smtp.sendgrid.net", Convert.ToInt32(587)); NetworkCredential networkCredential = new NetworkCredential(sendGridUsername, sendGridPassword); smtpClient.Credentials = (ICredentialsByHost)networkCredential; smtpClient.Send(message); } catch (Exception ex) { log.WriteLine("Failed to send notification. Exception is " + ex.Message); if (ex.InnerException != null) { log.WriteLine("Innber excpetion: " + ex.InnerException.Message); } } }
public UserModel(MundialitoUser user) { Username = user.UserName; Name = String.Format("{0} {1}", user.FirstName, user.LastName); Points = 0; Id = user.Id; Email = user.Email; }
public static AuthenticationProperties CreateProperties(MundialitoUser user) { IDictionary <string, string> data = new Dictionary <string, string> { { "userName", user.UserName }, { "firstName", user.FirstName }, { "lastName", user.LastName }, { "email", user.Email }, { "roles", string.Join(",", user.Roles.Select(role => role.Role.Name)) } }; return(new AuthenticationProperties(data)); }
public async Task <IHttpActionResult> GetExternalLogin(string provider, string error = null) { if (error != null) { return(Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error))); } if (!User.Identity.IsAuthenticated) { return(new ChallengeResult(provider, this)); } ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity); if (externalLogin == null) { return(InternalServerError()); } if (externalLogin.LoginProvider != provider) { Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); return(new ChallengeResult(provider, this)); } MundialitoUser user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey)); bool hasRegistered = user != null; if (hasRegistered) { Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); ClaimsIdentity oAuthIdentity = await UserManager.CreateIdentityAsync(user, OAuthDefaults.AuthenticationType); ClaimsIdentity cookieIdentity = await UserManager.CreateIdentityAsync(user, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user); Authentication.SignIn(properties, oAuthIdentity, cookieIdentity); } else { IEnumerable <Claim> claims = externalLogin.GetClaims(); ClaimsIdentity identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType); Authentication.SignIn(identity); } return(Ok()); }
private static void CreateAdminRoleAndUsers(MundialitoContext context) { var UserManager = new UserManager <MundialitoUser>(new UserStore <MundialitoUser>(context)); var RoleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context)); //Create Role Admin if it does not exist string name = "Admin"; if (!RoleManager.RoleExists(name)) { var roleresult = RoleManager.Create(new IdentityRole(name)); } var admin = new MundialitoUser(); admin.UserName = "******"; admin.FirstName = "Admin"; admin.LastName = "Admin"; admin.Email = "*****@*****.**"; var adminresult = UserManager.Create(admin, "123456"); //Add User Admin to Role Admin if (adminresult.Succeeded) { var result = UserManager.AddToRole(admin.Id, name); } var user = new MundialitoUser(); user.UserName = "******"; user.FirstName = "User1"; user.LastName = "User1"; user.Email = "*****@*****.**"; UserManager.Create(user, "123456"); var user2 = new MundialitoUser(); user2.UserName = "******"; user2.FirstName = "User2"; user2.LastName = "User2"; user2.Email = "*****@*****.**"; UserManager.Create(user2, "123456"); var user3 = new MundialitoUser(); user3.UserName = "******"; user3.FirstName = "User3"; user3.LastName = "User3"; user3.Email = "*****@*****.**"; UserManager.Create(user3, "123456"); }
private void CreateAdminRoleAndUsers(MundialitoContext context) { var RoleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context)); //Create Role Admin if it does not exist string name = "Admin"; if (!RoleManager.RoleExists(name)) { var roleresult = RoleManager.Create(new IdentityRole(name)); } //Create Admin user with password=123456 var user = new MundialitoUser(); user.UserName = WebConfigurationManager.AppSettings["AdminUserName"]; user.FirstName = WebConfigurationManager.AppSettings["AdminFirstName"]; user.LastName = WebConfigurationManager.AppSettings["AdminLastName"]; user.Email = WebConfigurationManager.AppSettings["AdminEmail"]; var adminresult = userManager.Create(user, "123456"); //Add User Admin to Role Admin if (adminresult.Succeeded) { var result = userManager.AddToRole(user.Id, name); } monkeyEnabled = !String.IsNullOrEmpty(WebConfigurationManager.AppSettings["MonkeyUserName"]); if (monkeyEnabled) { var monkey = new MundialitoUser(); monkey.UserName = WebConfigurationManager.AppSettings["MonkeyUserName"]; monkey.FirstName = "Monkey"; monkey.LastName = "Monk"; monkey.Email = "*****@*****.**"; userManager.Create(monkey, "monkey"); } }
public async Task <IHttpActionResult> RegisterExternal(RegisterExternalBindingModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity); if (externalLogin == null) { return(InternalServerError()); } MundialitoUser user = new MundialitoUser { UserName = model.UserName, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName }; user.Logins.Add(new IdentityUserLogin { LoginProvider = externalLogin.LoginProvider, ProviderKey = externalLogin.ProviderKey }); IdentityResult result = await UserManager.CreateAsync(user); IHttpActionResult errorResult = GetErrorResult(result); if (errorResult != null) { return(errorResult); } return(Ok()); }
public UserInfoViewModel GetUserInfo() { ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity); MundialitoUser user = UserManager.FindById(User.Identity.GetUserId()); if (user == null) { throw new Exception("Session expired. Please login again"); } return(new UserInfoViewModel { UserName = user.UserName, FirstName = user.FirstName, LastName = user.LastName, Email = user.Email, Roles = string.Join(",", user.Roles.Select(role => role.Role.Name)), HasRegistered = externalLogin == null, LoginProvider = externalLogin != null ? externalLogin.LoginProvider : null }); }
public async Task <ManageInfoViewModel> GetManageInfo(string returnUrl, bool generateState = false) { MundialitoUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user == null) { return(null); } List <UserLoginInfoViewModel> logins = new List <UserLoginInfoViewModel>(); foreach (IdentityUserLogin linkedAccount in user.Logins) { logins.Add(new UserLoginInfoViewModel { LoginProvider = linkedAccount.LoginProvider, ProviderKey = linkedAccount.ProviderKey }); } if (user.PasswordHash != null) { logins.Add(new UserLoginInfoViewModel { LoginProvider = LocalLoginProvider, ProviderKey = user.UserName, }); } return(new ManageInfoViewModel { LocalLoginProvider = LocalLoginProvider, UserName = user.UserName, Logins = logins, ExternalLoginProviders = GetExternalLogins(returnUrl, generateState) }); }
public NewBetModel UpdateBet(int id, UpdateBetModel bet) { var betToUpdate = new Bet(); betToUpdate.BetId = id; betToUpdate.HomeScore = bet.HomeScore; betToUpdate.AwayScore = bet.AwayScore; betToUpdate.CornersMark = "X"; betToUpdate.CardsMark = "X"; betToUpdate.GameId = bet.GameId; betToUpdate.UserId = userProivider.UserId; betValidator.ValidateUpdateBet(betToUpdate); betsRepository.UpdateBet(betToUpdate); betsRepository.Save(); Trace.TraceInformation("Updating Bet: {0}", betToUpdate); AddLog(ActionType.UPDATE, string.Format("Updating Bet: {0}", betToUpdate)); if (ShouldSendMail()) { MundialitoUser user = userManager.FindById(userProivider.UserId); Game game = gamesRepository.GetGame(bet.GameId); SendBetMail(betToUpdate); } return(new NewBetModel(id, bet)); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { using (UserManager <MundialitoUser> userManager = _userManagerFactory()) { MundialitoUser user = await userManager.FindAsync(context.UserName, context.Password); if (user == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } ClaimsIdentity oAuthIdentity = await userManager.CreateIdentityAsync(user, context.Options.AuthenticationType); ClaimsIdentity cookiesIdentity = await userManager.CreateIdentityAsync(user, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = CreateProperties(user); AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); context.Validated(ticket); context.Request.Context.Authentication.SignIn(cookiesIdentity); } }
public BetUser(MundialitoUser mundialitoUser) { UserName = mundialitoUser.UserName; FirstName = mundialitoUser.FirstName; LastName = mundialitoUser.LastName; }
public Bet(MundialitoUser user, Game game) { User = user; Game = game; }