public ActionResult Logar(LoginViewModel login) { //conflito 2 repository LoginRepository loginRepository = (LoginRepository)_unit.LoginRepository; //Validar nome consta Repositories/LoginRepository.cs, retorna objeto login, caso exista Login l = loginRepository.ValidarLogin(login.Username, login.Senha); if (l != null)//Se cliente localizado { //Se permissao == a ADMIN if (l.Permissao.Select(p => p.Permissao1 == "ADMIN").Single()) { //sessao tipo de usuario recebe Admin Session["TipoUsuario"] = "ADMIN"; //redirecionar pagina para controller Aluno, Cadastrar, #corrigir return(RedirectToAction("Listar", "Aluno")); } else { //Sessao tipousuario recebe aluno Session["TipoUsuario"] = "ALUNO"; //Sessao Nome recebe , nome do aluno Session["Nome"] = l.Aluno.First().Nome; //redirezionar para a Index do controller sessao return(RedirectToAction("Index", "Sessao")); } } else { //Se usuario e login estiverem incorretos, redirecionar para action Logar com a mensagem abaixo return(RedirectToAction("Logar")); } }
public override void OnAuthorization(HttpActionContext actionContext) { base.OnAuthorization(actionContext); if (actionContext.Request.Headers.Authorization == null) { actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized); } else { string encodedString = actionContext.Request.Headers.Authorization.Parameter; string decodedString = Encoding.UTF8.GetString(Convert.FromBase64String(encodedString)); string[] splitedString = decodedString.Split(new char[] { ':' }); string username = splitedString[0]; string password = splitedString[1]; //int password = Convert.ToInt32(splitedString[1]); int user = Int32.Parse(splitedString[0]); //Console.WriteLine(username); LoginRepository logrepo = new LoginRepository(); var userlist = logrepo.Login(user, password); if (userlist.Count == 1) { Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(username), null); } else { actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized); } } }
public LoginDboTest() { repository = new LoginRepository(DbContextFactory); dataService = new LoginDataService(repository, UnitOfWork); userRepository = new UserRepository(DbContextFactory); }
public void GetUserTest() { LoginRepository loginRepository = new LoginRepository(); User us = loginRepository.GetUser("Admin"); Assert.AreEqual(us.Email, "*****@*****.**"); }
//get produto ID public static LoginModelView GetLoginId(Int16 id) { Login objretorno = new Login(); LoginRepository tpprod = new LoginRepository(); objretorno = tpprod.Find(id); ////faz o de para: objEntity para objModelView //Mapper.CreateMap<Login, LoginModelView>(); //var vretorno = Mapper.Map<LoginModelView>(objretorno); //guarda a imagem no arquivo que chega até a tela como texto. // var img = objretorno.imagem; //faz o de para: objEntity para objModelView Mapper .CreateMap <Login, LoginModelView>(); //.ForMember(x => x.imagem, option => option.Ignore()); var vretorno = Mapper.Map <LoginModelView>(objretorno); //vretorno.arquivoimagem = img; return(vretorno); }
public async Task <ActionResult> Login(UserLogin model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } LoginRepository Log = new LoginRepository(); var result = await Log.GetUserLogin(model.Email, model.Password); //switch (result) //{ // case SignInStatus.Success: // return RedirectToLocal(returnUrl); // case SignInStatus.LockedOut: // return View("Lockout"); // case SignInStatus.RequiresVerification: // return RedirectToAction("SendCode", new { ReturnUrl = returnUrl }); // case SignInStatus.Failure: // default: // ModelState.AddModelError("", "Invalid login attempt."); // return View(model); //} if (result) { return(RedirectToLocal(returnUrl)); } else { ModelState.AddModelError("", "Invalid login attempt."); return(View(model)); } }
public ActionResult ConfirmChangePassword(string oldpass, string Pass, string cpass) { OfficerRepository orepo = new OfficerRepository(); LoginRepository lrepo = new LoginRepository(); Officer of = orepo.Get(Convert.ToInt32(Session["OfficerID"])); Logininfo log = lrepo.Get(Session["OfficerName"].ToString()); if (Session["Password"].ToString() == oldpass) { if (Pass != cpass) { ViewData["Message"] = "Password Didn't match"; } else { of.Officer_password = Pass; log.Login_Password = Pass; orepo.Update(of); lrepo.Update(log); ViewData["Message"] = "Password Updated Successfully"; Session["Officer"] = of; Session["Password"] = Pass; } } else { ViewData["Message"] = "Wrong Password"; } return(View("Empty")); }
public ActionResult Login(LoginViewModel viewModel) { if (ModelState.IsValid) { if (!(string.IsNullOrEmpty(viewModel.Email) || string.IsNullOrEmpty(viewModel.Password))) { LoginRepository objloginRep = new LoginRepository(); tblUserDetail objuserdetails = new tblUserDetail(); objuserdetails = objloginRep.GetUserForAuthentication(viewModel.Email); if (objuserdetails != null) { string passwordHash = HashHelper.ComputeSaltedHash(viewModel.Password, objuserdetails.PasswordSalt); if (string.Equals(passwordHash, objuserdetails.PasswordHash, StringComparison.Ordinal))// Validate User password; { SessionData.LoggedUserName = objuserdetails.UserName; return(RedirectToAction("GetAllUnProcessedRecords", "RoboticsProcess")); } else { ViewBag.LoginMessage = "The Employee ID or password is incorrect"; } } else { ViewBag.LoginMessage = "The Employee ID or password is incorrect"; } } } return(View()); }
private void SetLogin() { LoginRepository loginRepository = new LoginRepository(); if (loginRepository.CheckLogin(txb_email.Text, passwordBox.Password) == true) { this.Hide(); if (loginRepository.CheckAdmin(txb_email.Text, passwordBox.Password) == true) { ProjectManager projectManager = new ProjectManager(); projectManager.Show(); } else { DashboardMember dashboardMember = new DashboardMember(); dashboardMember.Show(); } } else { MessageBox.Show("Login Failed", "Warning!", MessageBoxButton.OK, MessageBoxImage.Information); passwordBox.Clear(); passwordBox.Focus(); } }
public ActionResult Login(CustomerAdminLogin cal) { if (ModelState.IsValid) { LoginRepository la = new LoginRepository(); string authResponse = la.LoginAuthenticate(cal); string eusername = cal.EnteredUsername; ViewBag.LoginResponse = authResponse; if (authResponse.Equals("Login Success")) { Session["username"] = eusername; return(RedirectToAction("Index", "Home")); } else if (authResponse.Equals("Admin Login Success")) { return(RedirectToAction("Orders", "Admin")); } else { return(View()); } } return(View()); }
public ActionResult Dashboard(string query) { loginRepo = new LoginRepository(); DashboardModel dashModel = new DashboardModel(); Dashboard dash = new Dashboard(); dash = loginRepo.GetDashboardDetails(query); dash.TweetList = new List <Bus.Tweet>(); dash.TweetList = loginRepo.GetAllTweets(); dashModel.Following = dash.Following; dashModel.Followers = dash.Followers; dashModel.TweetCount = dash.TweetCount; dashModel.Person = new Person { FullName = dash.Person.FullName, Id = dash.Person.Id }; dashModel.LoggedInUserId = dash.Person.UserId; Tweet tweet = new Tweet(); dashModel.TweetList = new List <Tweet>(); dashModel.TweetList = MapTweets(dash.TweetList); return(View(dashModel)); }
public ActionResult ServerList(FormCollection formCollection) { var token = formCollection["token"]; var loginRepo = new LoginRepository(); var serversRepo = new ServerRepository(); if (loginRepo.IsTokenExists(token)) { var servers = serversRepo.GetServers(1); var responce = new ServerListResponce(); responce.Servers = new List <ServerInfo>(); foreach (var server in servers) { responce.Servers.Add(new ServerInfo { ServerName = server.Name, ServerAddress = server.Address, UsersCount = server.UsersCount }); } var ms = new MemoryStream(); Serializer.Serialize(ms, responce); ms.Position = 0; return(new FileStreamResult(ms, "application/octet-stream")); } return(new EmptyResult()); }
protected void SendMail_Click(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(txtEmail.Text.ToString().Trim())) { LabelErrorMsg.Text = "Please enter your nokia user name"; LabelErrorMsg.Visible = true; txtEmail.Focus(); return; } LoginRepository login = new LoginRepository(); int sended = login.SendEmail(txtEmail.Text.ToString()); System.Threading.Thread.Sleep(1000); if (sended == 1) { LabelErrorMsg.Text = "Done you can go to your mail to get your password"; LabelErrorMsg.Visible = true; } else { LabelErrorMsg.Text = "User name not exist or Internet connction Error"; LabelErrorMsg.Visible = true; } }
/// <summary> /// 要進行登出,所以,清空本機快取資料 /// </summary> /// <returns></returns> public static async Task CleanRepositories() { #region 要進行登出,所以,清空本機快取資料 var fooSystemStatusRepository = new SystemStatusRepository(); await fooSystemStatusRepository.ReadAsync(); fooSystemStatusRepository.Item.AccessToken = ""; await fooSystemStatusRepository.SaveAsync(); var fooLoginRepository = new LoginRepository(); fooLoginRepository.Item = new Models.UserLoginResultModel(); await fooLoginRepository.SaveAsync(); var fooWorkingLogRepository = new WorkingLogRepository(); fooWorkingLogRepository.Items = new List <Models.WorkingLog>(); await fooWorkingLogRepository.SaveAsync(); var fooLeaveAppFormRepository = new LeaveAppFormRepository(); fooLeaveAppFormRepository.Items = new List <Models.LeaveAppForm>(); await fooLeaveAppFormRepository.SaveAsync(MainHelper.LeaveAppFormUserMode); await fooLeaveAppFormRepository.SaveAsync(MainHelper.LeaveAppFormManagerMode); #endregion }
//Purpose: To proces the login requests of clients into our application. //Input: 'userInfo' object of type 'UserInput.cs' //Output: a boolean variable representing the status of the login request. public dynamic Login(UserLoginInput userInfo) { ILoginRepository objLoginRepository = new LoginRepository(); var result = objLoginRepository.Login(userInfo.uName, userInfo.uPassword); return(result); }
public void TestUpdateEvent() { // Arrange LoginRepository loginRepo = new LoginRepository(true); loginRepo.IsUserLoginValid("TestUser", "TestPass"); EventRepository repo = new EventRepository(true); EventRecord record = new EventRecord() { Title = "Test Update Event", Description = "Test Update Description", StartTime = new DateTime(2020, 3, 25, 1, 0, 0), EndTime = new DateTime(2020, 3, 25, 2, 15, 0), LocX = 30.35, LocY = 120.74, UserId = 1, ListingId = 1 }; // Act string result = repo.UpdateEvent(record); // Assert Assert.AreEqual(result, string.Format("Successfully updated event {0}", record.Title)); }
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext) { base.OnAuthorization(actionContext); if (actionContext.Request.Headers.Authorization == null) { actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized); } else { string encodedString = actionContext.Request.Headers.Authorization.Parameter; string decodedString = Encoding.UTF8.GetString(Convert.FromBase64String(encodedString)); string[] arr = decodedString.Split(new char[] { ':' }); string username = arr[0]; string password = arr[1]; LoginRepository urepo = new LoginRepository(); if (username == urepo.Get(username).Login_Name&& password == urepo.Get(username).Login_Password) { Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(username), null); } else { actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized); } } }
public bool IsSuccess(Login login) { LoginRepository loginRepository = new LoginRepository(); bool isLogin = loginRepository.IsSuccessLog(login); return(isLogin); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { using (var repo = new LoginRepository()) { var user = await repo.GetByEmail(context.UserName); if (user == null) { context.SetError("invalid_grant", "The user name does not exist."); return; } if (user.PasswordHash == null) { PasswordManager.SetUserPassword(user, context.Password); await repo.Commit(); } else { bool valid = await PasswordManager.ValidatePassword(context.UserName, context.Password); if (!valid) { context.SetError("invalid_grant", "The username and password combination is wrong."); return; } } var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim(ClaimTypes.Name, user.Id.ToString())); context.Validated(identity); } }
private void Login() { LoginRepository loginRepository = new LoginRepository(); if (loginRepository.CheckLogin(textbox_email.Text, passwordbox_email.Password) == true) { this.Hide(); if (loginRepository.CheckAdmin(textbox_email.Text, passwordbox_email.Password) == true) { Dashboard dashboard = new Dashboard(); dashboard.Show(); } else { UIDashboardEmployee uiDashboardEmployee = new UIDashboardEmployee(); uiDashboardEmployee.Show(); } } else { MessageBox.Show("Login Failed", "Warning!", MessageBoxButton.OK, MessageBoxImage.Information); passwordbox_email.Clear(); passwordbox_email.Focus(); } }
//Отправка письма. True если письмо добавлено в базу. False если оно не соответствует требованиям public static bool SendLetter(MyMessage myMessage) { bool tooBig = false; for (int i = 0; i < myMessage.Tags.Count(); i++) { if (myMessage.Tags[i].Length > 10) { tooBig = true; break; } } if (myMessage == null || myMessage.Address.Length > 10 || myMessage.Sender.Length > 10 || myMessage.Title.Length > 50 || tooBig || LoginRepository.FindUser(myMessage.Sender) < 1 || LoginRepository.FindUser(myMessage.Address) < 1) { return(false); } int letterId = LoginRepository.AddMessageToDB(myMessage); if (myMessage.Tags != null) { for (int i = 0; i < myMessage.Tags.Count(); i++) { if (LoginRepository.CheckTag(myMessage.Tags[i]) == 0) { LoginRepository.AddTagToDB(myMessage.Tags[i]); } LoginRepository.AddTagLetter(LoginRepository.CheckTag(myMessage.Tags[i]), letterId); } } return(true); }
private void BtnChangePassword_Click(object sender, EventArgs e) { try { if (Validation.IsStringValid(this.txtOldPassword.Text) == true && Validation.IsStringValid(this.txtNewPassword.Text) == true) { LoginEntity le = new LoginEntity(this.em.Id, this.txtOldPassword.Text.ToString()); bool check = LoginRepository.SearchUser(le); if (check) { LoginRepository.UpdateUserPassword(le, this.txtNewPassword.Text.ToString()); MessageBox.Show("Password updated"); this.txtOldPassword.Text = ""; this.txtNewPassword.Text = ""; } else { MessageBox.Show("Insert Correct password"); } } else { MessageBox.Show("Insert Password"); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public IHttpActionResult Logar(Login login) { if (!string.IsNullOrEmpty(login.Email) && !string.IsNullOrEmpty(login.Senha)) { _login = Login; var consumidor = _login.LogarConsumidor(login.Email, login.Senha); var empresa = _login.LogarEmpresa(login.Email, login.Senha); if (consumidor == null && empresa == null) { return(BadRequest("E-mail ou senha incorreto.")); } if (consumidor != null) { var usuario = new UsuarioDTO() { Id = consumidor.Id_consumidor, Nome = consumidor.nomeConsumidor }; return(Ok(usuario)); } else { var usuario = new UsuarioDTO() { Id = empresa.Id_empresa, Nome = empresa.nomeUsuario }; return(Ok(usuario)); } } return(null); }
public ActionResult Index() { LoginRepository repo = new LoginRepository(); List <SelectListItem> listApplication = repo.GetListApplication(new { NetworkId = WebUtils.ParseUserLogon(HttpContext.User.Identity.Name) }); if (listApplication.Count > 1) { return(RedirectToAction(this.PageSettings.IndexPage, ApplicationSettings.Instance.Landing.LandingController)); } else { /* if more than one application * switch (listApplication[0].Value) * { * case "100": * ApplicationSettings.Instance.Landing.HomeController = "MVCTemplate"; * break; * case "200": * ApplicationSettings.Instance.Landing.HomeController = "Another Application"; * break; * } */ return(RedirectToAction(this.PageSettings.IndexPage, ApplicationSettings.Instance.Landing.HomeController)); } }
/// <summary> /// ViewModel 資料初始化 /// </summary> /// <returns></returns> private async Task ViewModelInit() { ChatContentCollection.Clear(); //ChatContentCollection.Add(new ChatContent //{ // 對話人圖片 = Girl, // 對話內容 = "我最近手機掉了,更換了電話號碼", // 對話類型 = 對話類型.他人, // 對話文字顏色 = Color.Green //}); //ChatContentCollection.Add(new ChatContent //{ // 對話人圖片 = Girl, // 對話內容 = "這是我的新電話號碼 0987654321", // 對話類型 = 對話類型.他人, // 對話文字顏色 = Color.Green //}); //ChatContentCollection.Add(new ChatContent //{ // 對話人圖片 = Boy, // 對話內容 = "妳現在在哪裡呀?", // 對話類型 = 對話類型.自己, // 對話文字顏色 = Color.Purple //}); var fooMyUser = new LoginRepository(); await fooMyUser.ReadAsync(); UserName = fooMyUser.Item.MyUser.UserName; await Task.Delay(100); }
private void Login() { LoginRepository loginRepository = new LoginRepository(); if (loginRepository.CheckLogin(txb_email.Text, pwb_password.Password) == true) { this.Hide(); if (loginRepository.CheckAdmin(txb_email.Text, pwb_password.Password) == true) { UIDashboardAdmin dashboard = new UIDashboardAdmin(); dashboard.Show(); } else if (loginRepository.CheckHeadDivision(txb_email.Text, pwb_password.Password) == true) { UIDashboardHeadDivision dashboard = new UIDashboardHeadDivision(); dashboard.Show(); } else { DashboardEmployee dashboard = new DashboardEmployee(); dashboard.Show(); } } else { MessageBox.Show("Login Failed", "Warning!", MessageBoxButton.OK, MessageBoxImage.Information); pwb_password.Clear(); pwb_password.Focus(); } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); //Add encoding compatibility Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); //Add cookie authentication services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => { options.LoginPath = new PathString("/login"); }); //Set project context ProjectContext pctx = new ProjectContext(Configuration.GetSection("XmlDataSources").GetSection("ProjectContext").Value); services.AddSingleton(pctx); //Set projects repository IProjectsRepository irp = new ProjectsRepository(pctx) as IProjectsRepository; services.AddScoped <IProjectsRepository, ProjectsRepository>(); //Set login repository ILoginRepository ilp = new LoginRepository(Configuration.GetSection("Administration").GetSection("Password").Value, Configuration.GetSection("Administration").GetSection("ClaimName").Value) as ILoginRepository; services.AddSingleton(ilp); //Set logger repository ILogger logger = new Logger(Configuration.GetSection("LogFilePath").Value) as ILogger; services.AddSingleton(logger); }
public async Task <LoginDTO[]> Get() { using (var repo = new LoginRepository()) { return((await repo.GetAll()).Select(x => new LoginDTO(x)).ToArray()); } }
public ActionResult Login(FormCollection formCollection) { var login = formCollection["login"]; var password = formCollection["pass"]; var repo = new LoginRepository(); var user = repo.Auth(login, password); LoginResponce loginResponce; if (user != null) { var r = new Random(DateTime.Now.Millisecond + login.GetHashCode()); var token = r.NextToken(); loginResponce = new LoginResponce { Logged = true, DisplayName = user.DisplayName, Token = token }; repo.WriteToken(user.id, token); repo.UpdateLoginDate(user.id); } else { loginResponce = new LoginResponce { Logged = false, Error = "Invalid login/password combination" }; } var ms = new MemoryStream(); Serializer.Serialize(ms, loginResponce); ms.Position = 0; return(new FileStreamResult(ms, "application/octet-stream")); }
public void Init() { database = new StartupDatabase(); database.InitializeEFInMemoryDatabase(true); mockPasswordEncryptionService = new Mock <IPasswordEncryptionService>(); loginRepository = new LoginRepository(mockPasswordEncryptionService.Object); }
/// <summary> /// Contructor for UnitOfWork that sets the reference to the repositories /// </summary> /// <param name="context"></param> public UnitOfWork(DataContext context) { _context = context; Stores = new StoreRepository(_context); Products = new ProductRepository(_context); HasA = new HasARepository(_context); Logins = new LoginRepository(_context); }
public bool Logout(LoginDataContract logoutData) { bool flag = false; using (LoginRepository loginRepo = new LoginRepository(new ChatDBDataContext())) { tbl_ChatUserLogin login = loginRepo.Get(logoutData.Username); if (login != null) { flag = ChangeUserStatus(ChatState.OFFLINE, login.Id); } } return flag; }
public int RegisterLogin(LoginDataContract loginData, int profileId) { int loginId = 0; using (LoginRepository loginRepo = new LoginRepository(new ChatDBDataContext())) { loginRepo.Create(new tbl_ChatUserLogin() { Username = loginData.Username, Password = loginData.Password, ProfileId = profileId }); loginRepo.Save(); loginId = loginRepo.Get(loginData.Username).Id; } return loginId; }
public void SetUp() { _context = new DataContext(); _store = new Store() {StoreName = "TestStore"}; _loginRepository = new LoginRepository(_context); _context.Database.Connection.ConnectionString = "Server=.\\SQLEXPRESS;Database=Pristjek220Data.DataContext; Trusted_Connection=True;"; _context.Database.ExecuteSqlCommand("dbo.TestCleanTable"); _context.Stores.Add(_store); _login = new Login() { Username = "******", Password = "******", Store = _store }; _context.Logins.Add(_login); _context.SaveChanges(); _passwd = new SecureString(); _passwd.AppendChar('p'); _passwd.AppendChar('a'); _passwd.AppendChar('s'); _passwd.AppendChar('s'); _passwd.AppendChar('w'); _passwd.AppendChar('d'); }
public void LoginRepositoryTest_Login_Entry() { LoginRepository loginRepository = new LoginRepository(); bool actual = loginRepository.Log(new Login { UserName="******", PassWord="******" }); Assert.IsTrue(actual); }
private void InstantiateLoginRepository() { _loginRepository = new LoginRepository(); }