public ActionResult Post(LoginModel login) { if (ModelState.IsValid) { DatabaseLogin dbLogin = new DatabaseLogin(DatabaseFactory); NimbusPrincipal loggedInUser; //verifica URL de redirecionamento if (String.IsNullOrWhiteSpace(login.RedirectURL) || !Uri.IsWellFormedUriString(login.RedirectURL, UriKind.Relative)) { login.RedirectURL = "/"; } //faz login no banco if (dbLogin.Authenticate(login.Email, login.Password, out loggedInUser, out _tempAuthResult)) { //Usuário e senha corretos, criar token de autenticação Guid token; //Cria token com validade de 7 dias string authToken = Token.GenerateToken( new NSCInfo() { TokenGenerationDate = DateTime.Now.ToUniversalTime(), TokenExpirationDate = DateTime.Now.AddDays(Const.CookieExpiryDays).ToUniversalTime(), UserId = (loggedInUser.Identity as NimbusUser).UserId }, out token); //Lembre-se de expirar o cookie também var loginCookie = new HttpCookie("nsc-session", authToken) { Expires = DateTime.Now.AddDays(Const.CookieExpiryDays) }; var modalHowToUseCookie = new HttpCookie("ShowHowToUse", "false") { Expires = DateTime.MaxValue }; //adiciona objeto do usuário logado à sessão Session[Const.UserSession] = loggedInUser; Response.Cookies.Add(loginCookie); Response.Cookies.Add(modalHowToUseCookie); return(Redirect(login.RedirectURL)); } else { //joga mensagem de erro login.ErrorMessage = "Usuário ou senha inválidos."; } } login.Password = ""; //limpa a senha antes de enviar return(View(login)); }
public void DataNameTest() { string Check = DatabaseLogin.GetString(1, "Gebruikersnaam"); Assert.AreEqual("Lin", Check); string Check2 = DatabaseLogin.GetString(1, "Naam"); Assert.AreEqual("Lin Lin", Check2); }
public void Setup() { var options = new DbContextOptionsBuilder <Context>(); options.UseInMemoryDatabase("PWMTESTDB"); PwmDbContext db = new PwmDbContext(new Context(options.Options)); db.USERDATA.AddRange(new List <USERDATA>() { UserFactory.CreateUser(new User() { UserName = "******", FullName = "fullName 1" }, "password1"), UserFactory.CreateUser(new User() { UserName = "******", FullName = "fullName 2" }, "password2"), UserFactory.CreateUser(new User() { UserName = "******", FullName = "fullName 3" }, "password3"), UserFactory.CreateUser(new User() { UserName = "******", FullName = "fullName 4" }, "password4"), UserFactory.CreateUser(new User() { UserName = "******", FullName = "fullName 5" }, "password5"), UserFactory.CreateUser(new User() { UserName = "******", FullName = "fullName 6" }, "password6"), }); db.SaveChanges(); factoryMock = new Mock <IPwmDbContextFactory>(); userInfoMock = new Mock <IUserInfo>(); factoryMock .Setup(x => x.Create()) .Returns(db); userInfoMock .SetupGet(mock => mock.User) .Returns(new User() { UserName = "******" }); login = new DatabaseLogin(factoryMock.Object); }
public void Create(string IP = null) { DatabaseLogin databaseLogin = new DatabaseLogin(); if (string.IsNullOrEmpty(IP)) { databaseLogin.IP = DatabaseParamaters.IsInDevelopment ? "localhost" : "cherryapp.pl"; } else { databaseLogin.IP = IP; } if (!string.IsNullOrEmpty(_login)) { databaseLogin.Login = _login; } else { databaseLogin.Login = _tenant.Tag; } if (!string.IsNullOrEmpty(_name)) { databaseLogin.Name = _name; } else { databaseLogin.Name = _tenant.Tag; } databaseLogin.Password = BCrypt.Net.BCrypt.HashPassword(Path.GetRandomFileName()); using (MySqlConnection Connection = new MySqlConnection(_configurationContext.ConnectionString)) using (MySqlCommand Command = new MySqlCommand($"CREATE USER '{databaseLogin.Login}'@'%' IDENTIFIED BY '{databaseLogin.Password}'; GRANT ALL ON cherry_{databaseLogin.Name}.* TO '{databaseLogin.Login}'@'%'; GRANT CREATE ON *.* TO '{databaseLogin.Login}'@'%';", Connection)) { Connection.Open(); Command.ExecuteNonQuery(); } //using (MySqlCommand Command = new MySqlCommand($"CREATE USER '{databaseLogin.Login}'@'{databaseLogin.IP}' IDENTIFIED BY '{databaseLogin.Password}'; GRANT ALL ON cherry_{databaseLogin.Name}.* TO '{databaseLogin.Login}'@'{databaseLogin.IP}'; GRANT CREATE ON *.* TO '{databaseLogin.Login}'@'{databaseLogin.IP}';", Connection)) //{ // Connection.Open(); // Command.ExecuteNonQuery(); //} _configurationContext.DatabaseLogins.Add(databaseLogin); _configurationContext.SaveChanges(); }
/// <summary> /// Gets the connection information needed to establish a connection to a MySQL database. /// </summary> public MySqlDbConnection() { //These objects will get the settings that are in //DatabaseSettings.Settings during construction _accountCredentials = new AccountLogin(); _databaseCredentials = new DatabaseLogin(); MySqlConnectionStringBuilder _connectionInformation = new MySqlConnectionStringBuilder(); _connectionInformation.Server = DatabaseCredentials.Server; _connectionInformation.UserID = AccountCredentials.Username; _connectionInformation.Password = AccountCredentials.Password; _connectionInformation.Database = DatabaseCredentials.DatabaseName; _connectionInformation.Port = uint.Parse(DatabaseCredentials.Port); _conInfo = _connectionInformation.ToString(); MySqlConnection testCon = new MySqlConnection(_conInfo); _canConnect = TryConnection(testCon); }
public ActionResult FacebookCallback(string redirect) { var fb = new FacebookClient(); FacebookOAuthResult fbResult; if (fb.TryParseOAuthCallbackUrl(Request.Url, out fbResult)) { if (fbResult.IsSuccess) { //pega nome, id, email e 3rd party id do facebook dynamic tokenResult = fb.Post("oauth/access_token", new { client_id = NimbusConfig.FacebookAppId, client_secret = NimbusConfig.FacebookAppSecret, redirect_uri = Request.Url.AbsoluteUri, //eh bizarro mas precisa disso code = fbResult.Code }); string accessToken = tokenResult.access_token; fb.AccessToken = accessToken; dynamic fbUserInfo = fb.Get("me?fields=first_name,last_name,id,email,third_party_id,birthday"); string fbEmail = fbUserInfo.email; //tenta achar o usuario no BD Model.ORM.User nimbusUser; using (var db = DatabaseFactory.OpenDbConnection()) { nimbusUser = db.Where <Model.ORM.User>(u => u.Email == fbEmail).FirstOrDefault(); if (nimbusUser == null) { //usuário sem conta nimbus, cria uma conta pra ele DateTime fbBirthday = Convert.ToDateTime(fbUserInfo.birthday, new DateTimeFormatInfo() { ShortDatePattern = "MM/dd/yyyy" }); string pathAvatar; dynamic fbAvatar = fb.Get("me/picture?redirect=0&type=large"); string fbAvatarUrl = fbAvatar.data.url; //precisa dessas idas e vindas por causa do fbAvatar ser dynamic if (fbAvatar.data.is_silhouette == true) { pathAvatar = "/images/av130x130/person_icon.png"; } else { var req = HttpWebRequest.Create(fbAvatarUrl); var respStream = req.GetResponse().GetResponseStream(); var img = new ImageManipulation(respStream); string thirdpartyid = fbUserInfo.third_party_id; pathAvatar = UserProfileController.UploadAvatar(img, thirdpartyid); } var newUser = new Model.ORM.User() { Email = fbEmail, FirstName = fbUserInfo.first_name, LastName = fbUserInfo.last_name, BirthDate = fbBirthday, AvatarUrl = pathAvatar, Password = "******" + fbUserInfo.id }; db.Insert(newUser); newUser.Id = (int)db.GetLastInsertId(); nimbusUser = newUser; } } //usuário já possui conta Nimbus, entao faz login pra ele Guid token; //Cria token com validade de 7 dias string authToken = Token.GenerateToken( new NSCInfo() { TokenGenerationDate = DateTime.Now.ToUniversalTime(), TokenExpirationDate = DateTime.Now.AddDays(Const.CookieExpiryDays).ToUniversalTime(), UserId = nimbusUser.Id }, out token); //Lembre-se de expirar o cookie também var loginCookie = new HttpCookie("nsc-session", authToken) { Expires = DateTime.Now.AddDays(Const.CookieExpiryDays) }; var modalHowToUseCookie = new HttpCookie("ShowHowToUse", "false") { Expires = DateTime.MaxValue }; //adiciona objeto do usuário logado à sessão Session[Const.UserSession] = DatabaseLogin.GetNimbusPrincipal(nimbusUser); Response.Cookies.Add(loginCookie); Response.Cookies.Add(modalHowToUseCookie); return(Redirect(redirect)); } //fim if (fbResult.IsSuccess) else { //erro no login do face if (fbResult.ErrorReason == "user_denied") { return(Redirect("/login?errormessage=" + Uri.EscapeDataString("É necessário autorizar o login pelo Facebook."))); } else { return(Redirect("/login?errormessage=" + Uri.EscapeDataString("Ocorreu um erro ao fazer login pelo Facebook."))); } } } else { //fim if (fb.TryParseOAuthCallbackUrl //usuario quis brincar com callback do facebook, redirect pra login sem nem mostrar erro return(Redirect("/login")); } }
public ConnectionStringBuilder(DatabaseLogin login) { ConnectionString = Build(login.IP, login.Name, login.Login, login.Password, !DatabaseParamaters.IsInDevelopment); }
async public Task <ActionResult> Login(LoginViewModel viewModel) { try { if (!ModelState.IsValid) { return(View("Login", viewModel)); } //if (string.IsNullOrEmpty(viewModel.UserName)) //{ // ModelState.AddModelError("", Resources.Resource.UsernameCannotBeBlank); //} //if (string.IsNullOrEmpty(viewModel.Password)) //{ // ModelState.AddModelError("", Resources.Resource.PasswordCannotBeBlank); //} string result = DatabaseLogin.User_Login(viewModel); if (result == "Tài khoản đã bị vô hiệu hóa") { // ModelState.AddModelError("", Resources.Resource.AccountIsNotActived); return(View("Login", viewModel)); } else if (result == "Đăng nhập thành công Admin") { System.Web.HttpContext.Current.Session[ApplicationConfig.AccountType] = ApplicationConfig.Admin; System.Web.HttpContext.Current.Session[ApplicationConfig.Language] = "VN"; System.Web.HttpContext.Current.Session[ApplicationConfig.username] = viewModel.UserName; System.Web.HttpContext.Current.Session[ApplicationConfig.UserInfo] = (Users)DatabaseLogin.GetUser(viewModel); // lấy toàn bộ thông tin } else if (result == "Đăng nhập thành công Customer") { System.Web.HttpContext.Current.Session[ApplicationConfig.AccountType] = ApplicationConfig.Customer; System.Web.HttpContext.Current.Session[ApplicationConfig.Language] = "VN"; System.Web.HttpContext.Current.Session[ApplicationConfig.username] = viewModel.UserName; System.Web.HttpContext.Current.Session[ApplicationConfig.UserInfo] = (Customer)DatabaseLogin.GetUser(viewModel); } else if (result == "Xin Mời Nhập Lại") { // ModelState.AddModelError("", Resources.Resource.UsernameOrPassswordIncorect); return(View("Login", viewModel)); } else { // ModelState.AddModelError("", Resources.Resource.LoginFail); return(View("Login", viewModel)); } Session[ApplicationConfig.username] = viewModel.UserName; //nếu đăng nhập thành công if (Session[ApplicationConfig.AccountType] == ApplicationConfig.Admin) { return(RedirectToAction("Index", "Home")); } else { return(RedirectToAction("UploadDocument", "Customer")); } } catch (Exception ex) { LogFile.Error(ex.ToString()); // Ghi thông tin ra file return(View("Login", viewModel)); } }