public AuthServer() { Service = new LoginService(); Service.Participate(); InitTestDb(); }
void Start() { loginService = FindObjectOfType<LoginService>(); loginService.OnLoginSuccess += LoginSuccessEventHandler; webSocketService = FindObjectOfType<WebSocketService>(); webSocketService.RegisterCommand(LootItemsDTO.COMMAND_NAME, LootItemsCallback, typeof(LootItemsDTO)); }
public void ForgotPassword_NormalEmail_True() { Mock<IUserEntityRepository> repository = new Mock<IUserEntityRepository>(); Mock<IPasswordService> passwordService = new Mock<IPasswordService>(); Mock<IMailService> mailService = new Mock<IMailService>(); Mock<ILoggerService> loggerService = new Mock<ILoggerService>(); mailService.Setup(o => o.SendMessage(It.IsAny<List<string>>(),It.IsAny<string>(),It.IsAny<string>(),It.IsAny<string>(),It.IsAny<bool>())).Returns(true); UserEntity user = new UserEntity(); user.ID = Guid.NewGuid(); user.FirstName = "Test"; repository.Setup(o => o.GetByEmail(It.IsAny<string>())).Returns(user); loggerService.Setup(o => o.Log(It.IsAny<Log>())); LoginService service = new LoginService( repository.Object, passwordService.Object, mailService.Object, loggerService.Object); bool flag = service.ForgotPassword("*****@*****.**"); Assert.IsTrue(flag); }
public LoginViewModel() { loginService = new LoginService(); courseService = new CourseService(); userDao = new UserDao(); courseDao = new CourseDao(); }
public LoginController( LoginService loginService, SignInInteraction signInInteraction, ISmsSender smsSender, ILoggerFactory loggerFactory) { _loginService = loginService; _signInInteraction = signInInteraction; _smsSender = smsSender; _logger = loggerFactory.CreateLogger<LoginController>(); }
protected void LogIn(object sender, EventArgs e) { //System.Diagnostics.Debug.WriteLine("Outside Session ID:" + HttpContext.Current.Session.SessionID); if (IsValid) { LoginService serv = new LoginService(UserName.Text, Password.Text, RememberMe.Checked); if (serv.Login()) Response.Redirect("../welcome.aspx"); } }
public SignUpController(SignUpService signUpService, LoginService loginService, ISmsSender smsSender, ILoggerFactory loggerFactory, IHostingEnvironment hostingEnvironment) { _signupService = signUpService; _loginService = loginService; _smsSender = smsSender; _logger = loggerFactory.CreateLogger<SignUpController>(); _hostingEnvironment = hostingEnvironment; }
public void Login ( string userName, string password, string cellphone, string placa, UserType type) { loginService = new LoginService (); loginService.SucceededEvent += LoadMainScene; loginService.FailedEvent += ShowError; //#if UNITY_EDITOR //loginService.StartService(Helpers.GetDeviceID (),"*****@*****.**","zxcvbn02","3012413857","SKX697",UserType.Generator,serverSettings); //loginService.StartService(Helpers.GetDeviceID (),"[email protected] ","zxcvbn02","","",UserType.Generator,serverSettings); //#elif UNITY_ANDROID loginService.StartService(Helpers.GetDeviceID (),userName,password,cellphone,placa,type,serverSettings); //#endif }
protected void Page_Load(object sender, EventArgs e) { if (!Request.IsAuthenticated) { LoginService service = new LoginService(); byte[] data = service.GetPublicKey(); using (RijndaelManaged rijAlg = new RijndaelManaged()) { string[] key = File.ReadAllLines(Server.MapPath("~/App_Data/AESKey.txt")); rijAlg.Key = Convert.FromBase64String(key[0]); rijAlg.IV = Convert.FromBase64String(key[1]); // Create a decrytor to perform the stream transform. ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV); // Create the streams used for decryption. using (MemoryStream msDecrypt = new MemoryStream(data)) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (StreamReader srDecrypt = new StreamReader(csDecrypt)) { // Read the decrypted bytes from the decrypting stream // and place them in a string. txtKey.Text = srDecrypt.ReadToEnd(); } } } } HttpCookie cookieUserName = Request.Cookies["UserName"]; HttpCookie cookiePassword = Request.Cookies["Password"]; if (cookieUserName != null) { // UserName.Attributes.Add("value", cookieUserName.Value); } if (cookiePassword != null) { // Password.Attributes.Add("value", cookiePassword.Value); } } else { lblusername.Text += " " + UserName; } }
private void ButtonEntrar_Click(object sender, RoutedEventArgs e) { LoginService service = new LoginService(); String login = TextLogin.Text; String pass = TextPass.Password; if (service.TryLogin(login, pass)) { Frame.Navigate(typeof(HomePage)); } else { MessageDialog dialog = new MessageDialog("Usuario e/ou senha invalidos."); } }
public object Any(List_Login request) { CommonResponse ecr = new CommonResponse(); ecr.initial(); try { LoginService ls = new LoginService(); ls.initial(auth, request, list_Login_Logic, ecr, this.Request.Headers.GetValues("Signature"), this.Request.RawUrl); } catch (Exception ex){ ecr.meta.code = 599; ecr.meta.message = "The server handle exceptions, the operation fails."; ecr.meta.errors.code = ex.HResult; ecr.meta.errors.field = ex.HelpLink; ecr.meta.errors.message = ex.Message.ToString(); } return ecr; }
public void ForgotPassword_NonExistingUser_True() { Mock<IUserEntityRepository> repository = new Mock<IUserEntityRepository>(); Mock<IPasswordService> passwordService = new Mock<IPasswordService>(); Mock<IMailService> mailService = new Mock<IMailService>(); Mock<ILoggerService> loggerService = new Mock<ILoggerService>(); repository.SetupSequence(o => o.GetByEmail(It.IsAny<string>())).Returns(null); LoginService service = new LoginService( repository.Object, passwordService.Object, mailService.Object, loggerService.Object); bool flag = service.ForgotPassword("*****@*****.**"); Assert.IsFalse(flag); }
private void btnRegister_Click(object sender, EventArgs e) { if (textBoxAccount1.Text == "") { MessageBox.Show("请先输入用户名:"); textBoxAccount1.Focus(); } if (textBoxPassword1.Text == "") { MessageBox.Show("请输入密码:"); textBoxPassword1.Focus(); } else if (textBox1.Text == "") { MessageBox.Show("请输入确认密码:"); textBox1.Focus(); } else if (!(textBoxPassword1.Text == textBox1.Text)) { MessageBox.Show("两次输入的密码不一致,请重新输入:"); textBoxPassword1.SelectAll(); textBox1.Text = ""; textBoxPassword1.Focus(); } else { loginService = new LoginService(); if (loginService.name_exist(textBoxAccount1.Text.ToString())) { MessageBox.Show("用户名已存在,请重新输入:"); textBoxAccount1.SelectAll(); textBoxPassword1.Clear(); textBox1.Clear(); textBoxAccount1.Focus(); } else { loginService.register(textBoxAccount1.Text.ToString(), textBoxPassword1.Text.ToString()); MessageBox.Show("注册成功,欢迎登陆"); this.Close(); } } }
protected void Login(object sender, EventArgs e) { LoginVMModel vmModel = new LoginVMModel(); ILoginInterface iLoginInterface = new LoginService(); Response.Cookies["UserName"].Value = Username.Text.Trim(); Response.Cookies["Password"].Value = password.Text.Trim(); vmModel.Username = Username.Text.Trim(); vmModel.Password = password.Text.Trim(); bool msg = iLoginInterface.ValidateCredentials(vmModel); if (msg) { Response.Redirect("TMSCoach.aspx"); } else { Label1.Visible = true; Label1.Text = "Login ID and Password is invalid."; } }
public async void LoginWithWindowHello() { IsBusy = true; try { var result = await LoginService.SignInWithWindowsHelloAsync(); if (result.IsOk) { EnterApplication(); return; } await DialogService.ShowAsync(result.Message, result.Description); } catch { await DialogService.ShowAsync("Windows Hello", "Windows Hello is unavailable, please use your username and password for now"); } IsBusy = false; }
public ActionResult Register(string name, string pwd, string phone, string validateCode, string roleName, string grad, //教师属性 string email, int categoryId, string degree, string experience) { ViewData["grads"] = CategroyService.FindByParent(0); ViewData["cates"] = CategroyService.FindByParent(1); Users student = new Users { name = name, pwd = pwd, phone = phone, roleName = roleName, grad = grad, email = email, categoryId = categoryId, degree = degree, experience = experience }; if (validateCode != base.GetSessionByKey("ValidateCode")) { ViewData["resp"] = base.RespResult(false, "验证码错误"); } else { string message = string.Empty; Users user = LoginService.Register(student, ref message); if (string.IsNullOrEmpty(message)) { FormsAuthent(user); ViewData["resp"] = base.RespResult(true, "注册成功!"); } else { ViewData["resp"] = base.RespResult(false, message); } } return(View()); }
/// <summary> /// 处理 WebSocket 信道 GET 请求 /// </summary> /// /// <remarks> /// GET 请求表示客户端请求进行信道连接,此时会向 SDK 申请信道连接地址,并且返回给客户端 /// 如果配置指定了要求登陆,还会调用登陆服务来校验登陆态并获得用户信息 /// </remarks> private void HandleGet(ITunnelHandler handler, TunnelHandleOptions options) { Configuration config = ConfigurationManager.CurrentConfiguration; Tunnel tunnel = null; UserInfo user = null; // 要求登录态,获取用户信息 if (options?.CheckLogin == true) { try { LoginService loginService = new LoginService(Request, Response); user = loginService.Check(); } catch { // 要求检查登录态的话,发生异常就结束了 return; } } // 申请 WebSocket 信道连接地址 TunnelAPI tunnelApi = new TunnelAPI(); try { tunnel = tunnelApi.RequestConnect(BuildReceiveUrl()); } catch (Exception e) { Response.WriteJson(new { error = e.Message }); throw e; } // 输出 URL 结果 Response.WriteJson(new { url = tunnel.ConnectUrl }); handler.OnTunnelRequest(tunnel, user); }
protected override void OnResume() { base.OnResume(); database = new SQLiteRepository(); contactRepository = new ContactRepository(database); messageRepository = new MessageRepository(database); configRepository = new ConfigRepository(database); configuracion = configRepository.GetConfig(); errorText = new ErrorText(); loginService = new LoginService(); messageService = new MessageService(); count = 0; try { client = loginService.Connect(); if (client.IsUserAuthorized()) { usuario = client.Session.TLUser; } } catch (Exception ex) { this.FinishAffinity(); } speechReco = SpeechRecognizer.CreateSpeechRecognizer(this.ApplicationContext); speechReco.SetRecognitionListener(this); intentReco = new Intent(RecognizerIntent.ActionRecognizeSpeech); intentReco.PutExtra(RecognizerIntent.ExtraLanguagePreference, "es"); intentReco.PutExtra(RecognizerIntent.ExtraCallingPackage, this.PackageName); intentReco.PutExtra(RecognizerIntent.ExtraLanguageModel, RecognizerIntent.LanguageModelWebSearch); intentReco.PutExtra(RecognizerIntent.ExtraMaxResults, 1); gestureDetector = new GestureDetector(this); toSpeech = new TextToSpeech(this, this); }
static void Main(string[] args) { var ls = new LoginService(); var codeStream = ls.GetQRCode(); var fs = new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\WX二维码.png", FileMode.Create); fs.Write(codeStream, 0, codeStream.Length); while (true) { var loginResult = ls.LoginCheck(); if (loginResult is Stream) { //已扫描 未登录 Console.WriteLine("please click login btton in you phone!"); } else if (loginResult is string) { //已完成登录 ls.GetSidUid(loginResult as string); break; } } var wxService = WXService.Instance; wxService.InitData(); var allFriend = wxService.AllContactCache; wxService.Listening(msgs => { foreach (var msg in msgs) { // do you logic } }); }
private void LoadSchedule() { logService.Add("Reading credentials file..."); // Login user and set cookies ConfigService credentialService = new ConfigService(); config = credentialService.GetCredentials(); logService.Add("Success"); logService.Add("Logging in user..."); LoginService loginService = new LoginService(config.LoginUrl); cookieContainer = loginService.Authorize(config.Credential); logService.Add("Success"); logService.Add("Parsing schedule..."); // Get Schedule (rozvrh) string url = config.ScheduleUrl; if ((DateTime.Today.DayOfWeek.ToString() == "Saturday" || DateTime.Today.DayOfWeek.ToString() == "Sunday") && config.DisplayNextWeekFromSaturday == true) { url += "?s=next"; } ScheduleService scheduleService = new ScheduleService(cookieContainer, url);; scheduleService.GetHtmlPage(); Schedule schedule = scheduleService.GetSchedule(); logService.Add("Success"); logService.Add("Generating schedule..."); ScheduleGeneratorService scheduleGenerator = new ScheduleGeneratorService(schedule, ScheduleContentGrid); scheduleGenerator.GenerateSchedule(); logService.Add("Success"); }
static void Main(string[] args) { bool condition = true; ICommandLineInterface CLI; //SalesCommandscommon sls = new SalesCommandscommon(); LoginService Ls = new LoginService(); User Usr = Ls.LogIndatabase(); if (Usr.Root) { CLI = new AdminCommandscommon(); } else { CLI = new SalesCommandscommon(); } CLI.Dictfilling(); do { CLI.PrintCommands(); Console.WriteLine("введите команду"); Console.WriteLine(CLI.GetType()); string command = Console.ReadLine(); if (command == "exit") { condition = false; } else { CLI.ExecuteCommands(command); } }while (condition); //AdminCommandsDelete test = new AdminCommandsDelete(); // test.CommandsRealization(adm); Console.ReadKey(); }
/// <summary> Callback when all services are loaded on the server.</summary> public override void OnStart() { Log.Info("Eternus.Game.OnStart()"); string s = gameStateDB != null?gameStateDB.ToString() : "null"; // Log.Info($"DB is {s}"); login = GetService <LoginService>(); sync = GetService <SyncService>(); entity = GetService <EntityService>(); map = GetService <MapService>(); liveGames = new Heap <LiveGame>(); gamesByUsername = new Dictionary <string, LiveGame>(); gamesByGUID = new Dictionary <Guid, LiveGame>(); loggedOut = new ConcurrentSet <LiveGame>(); entity.RegisterUserEntityInfo <GameState>(); login.userInitializer += Initialize; // statCalc = DB.Local("Content").Get<StatCalc>("StatCalc"); DB.Drop <GameState>(); DB.Drop <UnitRecord>(); DB.Drop("Inventory"); // @TODO: For testing, remove for release DB.Drop <List <LoginService.UserAccountCreation> >(); //JsonObject test = new JsonObject( // "str", 5, "dex", 12, // "maxHealth", 200, // "recHealth", 1.5, // "what", 123123 //); //JsonObject result1 = statCalc.SmartMask(test, statCalc.ExpStatRates); //JsonObject result2 = statCalc.SmartMask(test, statCalc.CombatStats); //Log.Info(result1); //Log.Info(result2); }
async void OnLoginButtonClicked(object sender, EventArgs e) { messageLabel.Text = ""; if (usernameEntry.Text == "" || passwordEntry.Text == "") { messageLabel.Text = "Username e password obbligatori"; return; } buttonLogin.IsEnabled = false; indicatorLoader.IsRunning = true; var content = await RestService.DoLogin(usernameEntry.Text, passwordEntry.Text); indicatorLoader.IsRunning = false; buttonLogin.IsEnabled = true; if (content != null) { if (content.success) { if (content.message != null) { messageLabel.Text = content.message; } if (content.data != null && content.data.Count >= 4) { LoginService.SaveUserInfo(content.data); passwordEntry.Text = string.Empty; Navigation.InsertPageBefore(new MainPage(), this); await Navigation.PopAsync(); } } else { messageLabel.Text = content.message; } } }
private async Task StartUpload() { try { var wasLoggedIn = await LoginService.RefreshTokens(); if (!wasLoggedIn) { MessageBox.Show("To upload photos, you need an upload token from the Mapillary service. Please retry login.", "Unable to get upload token", MessageBoxButton.OK); return; } m_uploadQueue = new Queue <Photo>(); uploadMsg.Visibility = Visibility.Collapsed; errorMsg.Text = ""; errorMsg.Visibility = Visibility.Collapsed; m_numFailed = 0; if (m_viewModel != null && m_viewModel.NumPhotos > 0) { countToUpload = m_viewModel.NumPhotos; countUploaded = 0; UpdateTotalStatus(); errorMsg.Text = ""; errorMsg.Visibility = Visibility.Visible; App.SetLockMode(true); m_isStopped = false; foreach (var upload in m_viewModel.PhotoList.ToList()) { m_uploadQueue.Enqueue(upload); } await ProcessQueue(); } } catch (Exception ex) { errorMsg.Text = "Upload ERROR: " + ex.Message; throw; } }
// GET: PurchaseItems/AddAllLowStockToPurchaseItems public ActionResult AddAllLowStockToPurchaseItems() { if (!LoginService.IsAuthorizedRoles("clerk")) { return(RedirectToAction("Index", "Home")); } var lowstockitems = uow.InventoryItemRepository.Get(filter: i => i.InStoreQty < i.ReorderLvl, includeProperties: "Item"); // need to change later Supplier s = uow.SupplierRepository.GetByID("ALPA"); var purchaseItems = uow.PurchaseItemRepository.Get(filter: x => x.PurchaseOrder == null, includeProperties: "Tender.Item"); foreach (InventoryItem ii in lowstockitems) { int flag = 0; //check if existing item is already in purchaseItems foreach (PurchaseItem pi in purchaseItems) { if (ii.Item == pi.Tender.Item) { pi.Qty = pi.Qty + ii.ReorderQty; uow.PurchaseItemRepository.Update(pi); uow.Save(); flag = 1; } } if (flag == 0) { PurchaseItem PI = new PurchaseItem(ii.Item, s, ii.ReorderQty, uow); uow.PurchaseItemRepository.Insert(PI); uow.Save(); Debug.WriteLine("Created Purchase Item"); } } return(RedirectToAction("Index")); }
/// <summary> /// 驗證使用者登入 /// </summary> /// <returns></returns> public IHttpActionResult Post(Infrastructure.ViewModel.Login.LoginRequest requestData) { var content = new ResultBaseModel <Infrastructure.ViewModel.Login.LoginResponse>(); try { var service = new LoginService(); // var requestData = JsonConvert.DeserializeObject<Infrastructure.ViewModel.Login.LoginRequest>(strAccess); requestData.PhoneID = requestData.PhoneID.Replace("-", "").ToLower(); var result = service.LoginProxy(requestData); if (result != null) { content.Success = true; content.Data = new Infrastructure.ViewModel.Login.LoginResponse[1] { result }; content.Message = "登入成功"; content.State = LogState.Suscess; return(Ok(content)); } else { content.Success = false; content.Data = new Infrastructure.ViewModel.Login.LoginResponse[0]; content.Message = "登入失敗"; content.State = LogState.NoAccount; return(Ok(content)); } } catch (Exception ex) { content.Success = false; content.Data = new Infrastructure.ViewModel.Login.LoginResponse[0]; content.Message = ex.Message; content.State = LogState.Error; return(Content(HttpStatusCode.Forbidden, content)); } }
public IActionResult AfterLogin([FromServices] LoginService ls, string username, string password, [FromServices] BrowseService bs, [FromServices] CartService cs, string query1 = "") { int val = ls.Login(username, password, HttpContext.Session); if (val == 1) { TempData["err"] = "Username does not exist"; return(RedirectToAction("Login", "Home")); } else if (val == 2) { TempData["err"] = "Incorrect password"; return(RedirectToAction("Login", "Home")); } else if (val == 3) { ViewData["username"] = username; HttpContext.Session.SetString("username", username); ViewData["username"] = HttpContext.Session.GetString("username"); } if (ViewData["username"] != null) { List <Product> products = bs.GetProducts(query1); ViewData["products"] = products; var customerId = HttpContext.Session.GetInt32("customerId") ?? 0; var sessionCart = HttpContext.Session.GetString("Cart"); if (sessionCart != null) { var cart = JsonConvert.DeserializeObject <Cart>(sessionCart); cs.AddCartWithCustomer(customerId, cart); ViewData["ItemCount"] = cart.Quantity; } else { ViewData["ItemCount"] = cs.GetNumberOfCartItem(customerId); } } return(View()); }
public void Correctly_provides_feedback_if_login_is_unsuccessful() { MockRepository mocks = new MockRepository(); ILoginChecker checker = mocks.CreateMock <ILoginChecker>(); IAuthenticationService authenticationService = mocks.CreateMock <IAuthenticationService>(); ISystemUserRepository repository = mocks.CreateMock <ISystemUserRepository>(); using (mocks.Record()) { Expect.Call(checker.IsValidUser("*****@*****.**", "pass", repository)).Return(false); } using (mocks.Playback()) { ILoginService loginService = new LoginService(checker, authenticationService, null); string userFeedback = loginService.Login("*****@*****.**", "pass", false, repository); Assert.That(userFeedback, Is.EqualTo("Invalid e-mail address/password: Please try again")); } mocks.VerifyAll(); }
public void Application_AuthenticateRequest(Object sender, EventArgs e) { var cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]; if (cookie == null) return; var decryptedCookie = FormsAuthentication.Decrypt(cookie.Value); if (decryptedCookie == null) return; using (var context = new UserContext()) { var userRepository = new UserRepository(context); var identity = userRepository.Find(decryptedCookie.Name); var loginService = new LoginService(userRepository); if (loginService.CheckDate()) { var principal = new GenericPrincipal(identity, new string[] {"Member"}); Thread.CurrentPrincipal = HttpContext.Current.User = principal; } else { FormsAuthentication.SignOut(); } } }
private void button1_Click(object sender, EventArgs e) { Login login = new Login(); LoginService service = new LoginService(); String userName = textBox1.Text; String password = textBox2.Text; login.UserName = userName; login.Password = password; int rows = service.NewLogin(login); if (rows > 0) { MessageBox.Show("Login created"); } else { MessageBox.Show("Login creation failed"); } }
public void Correctly_logs_users_out_and_redirects_them_to_the_login_page() { MockRepository mocks = new MockRepository(); IWebContext context = mocks.CreateMock <IWebContext>(); IAuthenticationService authenticationService = mocks.CreateMock <IAuthenticationService>(); using (mocks.Record()) { authenticationService.Logout(); Expect.Call(authenticationService.GetLoginUrl()).Return("Login.aspx"); context.Redirect("Login.aspx"); } using (mocks.Playback()) { ILoginService loginService = new LoginService(null, authenticationService, context); loginService.Logout(); } mocks.VerifyAll(); }
public LoginViewModel() { //_page = page; var _loginService = new LoginService(); //this.LoginCommand=new Command(() => Navigation.Push(new HomePage())); this.LoginCommand = new Command(async(nothing) => { var result = await _loginService.LoginAsync(Username, Password); if (result.USER_ID > 0) { Application.Current.Properties["USER_ID"] = result.USER_ID; await Navigation.PushAsync(new MainPage()); } else { await Navigation.DisplayAlert("错误", "输入的用户名或密码错误!", "确定"); } }); //_navigationService = navigationService; }
public void login(object sender, EventArgs e) { string userName = userTxt.Text; string password = passwordTxt.Text; if (userName.Equals("") || password.Equals("")) { } else { LoginService loginService = new LoginService(); bool isValidPerson = loginService.Login(userName, password); if (isValidPerson) { Session["user"] = userName; Response.Redirect("DisplayStudents.aspx?user = " + userName); } else { } } }
public static void Init() { _serializer = new _Serializer(); _serverCallback = new ServerCallback(); _serverManager = ServerManager.Instance; _messageManager = new MessageManager(); _globalEvent = new GlobalEvent(); _globalEvent.Init(); _viewLib = _serverManager._viewLib; _uiManager = _serverManager._uiManager; _loginService = new LoginService(); _sceneManager = new SceneManager(); _sceneService = new SceneService(); _loginManager = new LoginManager(); _gameManager = GameManager._instance; _gameReference = _gameManager._gameReference; _blockGenerator = new BlockGenerator(); _gameData = new GameData(); _randomUtil = new RandomUtil(); _excelUtil = new ExcelUtil(); }
public ActionResult Index(UserDTO entity) { if (ModelState.IsValid) { LoginService logServ = new LoginService(); Custom_UserDTO user = logServ.CheckUser(entity); if (user != null) { FormsAuthentication.SetAuthCookie(user.usrName, false); Session["userName"] = user.usrName; Session["userID"] = user.usrID; Session["userFullName"] = user.empName + " " + user.empSurname; return(RedirectToAction("Index", "Document")); } else { ModelState.AddModelError(string.Empty, "İstifadəçi mövcud deyil."); } } return(View("Index")); }
public LoginAppService( LoginService loginService, ACodeService aCodeService, SignatureChecker signatureChecker, SignInManager <IdentityUser> signInManager, IDataFilter dataFilter, IConfiguration configuration, IHttpClientFactory httpClientFactory, IUserInfoRepository userInfoRepository, IJsonSerializer jsonSerializer, IWeChatMiniProgramAsyncLocal weChatMiniProgramAsyncLocal, IMiniProgramUserRepository miniProgramUserRepository, IMiniProgramLoginNewUserCreator miniProgramLoginNewUserCreator, IMiniProgramLoginProviderProvider miniProgramLoginProviderProvider, IDistributedCache <MiniProgramPcLoginAuthorizationCacheItem> pcLoginAuthorizationCache, IDistributedCache <MiniProgramPcLoginUserLimitCacheItem> pcLoginUserLimitCache, IOptions <IdentityOptions> identityOptions, IdentityUserManager identityUserManager, IMiniProgramRepository miniProgramRepository) { _loginService = loginService; _aCodeService = aCodeService; _signatureChecker = signatureChecker; _signInManager = signInManager; _dataFilter = dataFilter; _configuration = configuration; _httpClientFactory = httpClientFactory; _userInfoRepository = userInfoRepository; _jsonSerializer = jsonSerializer; _weChatMiniProgramAsyncLocal = weChatMiniProgramAsyncLocal; _miniProgramUserRepository = miniProgramUserRepository; _miniProgramLoginNewUserCreator = miniProgramLoginNewUserCreator; _miniProgramLoginProviderProvider = miniProgramLoginProviderProvider; _pcLoginAuthorizationCache = pcLoginAuthorizationCache; _pcLoginUserLimitCache = pcLoginUserLimitCache; _identityOptions = identityOptions; _identityUserManager = identityUserManager; _miniProgramRepository = miniProgramRepository; }
static void Main(string[] args) { // 初始化 PKG 模板生成物代码 序列化的 id:type 映射 PKG.AllTypes.Register(); // 创建 libuv 运行核心循环 var loop = new xx.UvLoop(); // 初始化 rpc 管理器, 设定超时参数: 精度(ms), 默认超时 ticks( duration = 精度ms * ticks ) loop.InitRpcManager(1000, 5); // 初始化 peer活动 超时管理器. 精度ms, 计时 ticks 最大值, 默认 ticks ( duration = 精度ms * ticks ) loop.InitTimeoutManager(1000, 30, 5); // 创建登陆服务实例 var loginService = new LoginService(loop); Console.WriteLine("server_login running..."); // 开始运行 loop.Run(); }
public async void LoginWithWindowHello() { IsBusy = true; try { var result = await LoginService.SignInWithWindowsHelloAsync(); if (result.IsOk) { EnterApplication(); return; } await DialogService.ShowAsync(result.Message, result.Description); } catch (Exception) { await DialogService.ShowAsync("Windows Hello", "Windows Hello is currently unavailable."); } IsBusy = false; }
public IHttpActionResult Login([FromBody] UserCredential userCredential) { LoginService login = new LoginService() { userCredential = userCredential }; LoginResponseDTO loginResponse = new LoginResponseDTO(); loginResponse = login.loginService(); if (loginResponse.Messages.Contains("User does not exist") || loginResponse.Messages.Contains("Could not Create Token")) { return(Content(HttpStatusCode.NotFound, loginResponse.Messages)); } else if (loginResponse.Messages.Contains("Incorrect Credentials")) { return(Content(HttpStatusCode.Unauthorized, loginResponse.Messages)); } return(Ok(loginResponse)); }
public async void LoginWithPassword() { IsBusy = true; var result = ValidateInput(); if (result.IsOk) { if (await LoginService.SignInWithPasswordAsync(UserName, Password)) { if (!LoginService.IsWindowsHelloEnabled(UserName)) { await LoginService.TrySetupWindowsHelloAsync(UserName); } SettingsService.UserName = UserName; EnterApplication(); return; } } await DialogService.ShowAsync(result.Message, result.Description); IsBusy = false; }
public async Task SignInAsync_SavesCredsToStore_WhenSigninOk() { //Arrange base.AddRouteHandler("/auth/token", (req, res) => res.WriteJson(new { access_token = "123456" })); var clientCredentialStore = new InMemoryClientCredentialStore(); var loginService = new LoginService(new RestClient(new NssHttpClientFactory(), clientCredentialStore)); //Act var result = await loginService.SignInAsync(Url, "username", "password"); //Assert Assert.That(result, Is.True); Assert.That(clientCredentialStore.HasCredentialsAsync, Is.True); var creds = await clientCredentialStore.GetAsync(); Assert.That(creds, Is.Not.Null); Assert.That(creds.AccessToken, Is.EqualTo("123456")); Assert.That(creds.BaseUrl, Is.EqualTo(Url)); Assert.That(creds.Password, Is.EqualTo("password")); Assert.That(creds.RetryAuthenticateFailed, Is.False); Assert.That(creds.Username, Is.EqualTo("username")); }
public ActionResult UpdateCollectionPoint(string id) { UnitOfWork uow = new UnitOfWork(); if (!LoginService.IsAuthorizedRoles("head", "rep")) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } string deptId = loginService.StaffFromSession.DepartmentID; Department department = uow.DepartmentRepository.GetByID(deptId); CollectionPoint collectionPoint = uow.CollectionPointRepository.GetByID(int.Parse(id)); if (collectionPoint != null) { department.CollectionPoint = collectionPoint; uow.DepartmentRepository.Update(department); uow.Save(); Debug.WriteLine("Collection point for " + department.DeptName + " updated to " + collectionPoint.Location); } return(RedirectToAction("Dashboard", "Home")); }
/// <summary> /// hàm thực hienj việc lưu lại thông itn /// </summary> /// <param name="sender"></param> /// <param name="eventArgs"></param> private void txtUserName_LostFocus(object sender, EventArgs eventArgs) { try { if (_oldUid != Utility.sDbnull(txtUserName.Text)) { _oldUid = Utility.sDbnull(txtUserName.Text); globalVariables.UserName = _oldUid; bool isAdmin = new LoginService().isAdmin(Utility.sDbnull(_oldUid)); DataBinding.BindDataCombobox(cboKhoaKCB, THU_VIEN_CHUNG.LaydanhsachKhoaKhidangnhap(globalVariables.UserName, Utility.Bool2byte(isAdmin)), DmucKhoaphong.Columns.MaKhoaphong, DmucKhoaphong.Columns.TenKhoaphong, "---Khoa làm việc---", false); cboKhoaKCB.SelectedIndex = Utility.GetSelectedIndex(cboKhoaKCB, PropertyLib._AppProperties.Makhoathien); } } catch (Exception ex) { Utility.ShowMsg("Lỗi:" + ex); } }
public App() { Device.SetFlags(new string[] { "MediaElement_Experimental", "RadioButton_Experimental", "Shell_UWP_Experimental", "Visual_Experimental", "CollectionView_Experimental", "FastRenderers_Experimental" }); InitializeComponent(); if (Preferences.Get("AutoLogin", false)) { User user = new User { Username = Preferences.Get("username", String.Empty), PasswordSha1 = Preferences.Get("password", string.Empty) }; LoginService loginService = new LoginService(); if (!loginService.Login(user)) { Preferences.Set("AutoLogin", false); } } if (Preferences.ContainsKey("lang")) { LanguageManager.SetLanguage(Preferences.Get("lang", "en")); Current.MainPage = new NavigationPage(new HomePage()) { BarBackgroundColor = StaticVariables.NavBarBackgroundColor, BarTextColor = StaticVariables.NavBarTextColor, }; } else { Current.MainPage = new NavigationPage(new SelectLanguagePage()) { BarBackgroundColor = StaticVariables.NavBarBackgroundColor, BarTextColor = StaticVariables.NavBarTextColor, }; } }
public void RegisterUser_EmailInUse_NotRegistered() { Mock<IUserEntityRepository> repository = new Mock<IUserEntityRepository>(); Mock<IPasswordService> passwordService = new Mock<IPasswordService>(); Mock<IMailService> mailService = new Mock<IMailService>(); Mock<ILoggerService> loggerService = new Mock<ILoggerService>(); repository.Setup(o => o.isEmailInUse(It.IsAny<string>())).Returns(true); LoginService service = new LoginService( repository.Object, passwordService.Object, mailService.Object, loggerService.Object); UserEntity user = new UserEntity(); user.ID = Guid.NewGuid(); user.FirstName = "Test"; user.UserPassword = "******"; user.Email = "*****@*****.**"; user = service.RegisterUser(user); Assert.IsNull(user); }
public void RegisterUser_EmptyPassword_NotRegistered() { Mock<IUserEntityRepository> repository = new Mock<IUserEntityRepository>(); Mock<IPasswordService> passwordService = new Mock<IPasswordService>(); Mock<IMailService> mailService = new Mock<IMailService>(); Mock<ILoggerService> loggerService = new Mock<ILoggerService>(); repository.Setup(o => o.isEmailInUse(It.IsAny<string>())).Returns(false); passwordService.SetupSequence(o => o.GenerateCredentials(It.IsAny<UserEntity>())).Returns(null); LoginService service = new LoginService( repository.Object, passwordService.Object, mailService.Object, loggerService.Object); UserEntity user = new UserEntity(); user.ID = Guid.NewGuid(); user.FirstName = "Test"; user.UserPassword = string.Empty; user.Email = "*****@*****.**"; UserEntity retuser = service.RegisterUser(user); Assert.IsNull(retuser); }
public AccountController(UserService<SigmaUser> userService, LoginService<SigmaUser> loginService, IEmailService emailService) { UserService = userService; LoginService = loginService; EmailService = emailService; }
public void RegisterUser_NullUser_NotRegistered() { Mock<IUserEntityRepository> repository = new Mock<IUserEntityRepository>(); Mock<IPasswordService> passwordService = new Mock<IPasswordService>(); Mock<IMailService> mailService = new Mock<IMailService>(); Mock<ILoggerService> loggerService = new Mock<ILoggerService>(); LoginService service = new LoginService( repository.Object, passwordService.Object, mailService.Object, loggerService.Object); UserEntity retuser = service.RegisterUser(null); Assert.IsNull(retuser); }
public void RegisterUser_ValidUser_Registered() { UserEntity entity = new UserEntity(); entity.ID = Guid.NewGuid(); entity.FirstName = "Test"; entity.UserPassword = "******"; entity.Email = "*****@*****.**"; Mock<IUserEntityRepository> repository = new Mock<IUserEntityRepository>(); Mock<IPasswordService> passwordService = new Mock<IPasswordService>(); Mock<IMailService> mailService = new Mock<IMailService>(); Mock<ILoggerService> loggerService = new Mock<ILoggerService>(); repository.Setup(o => o.Insert(It.IsAny<UserEntity>())); repository.Setup(o => o.isEmailInUse(It.IsAny<string>())).Returns(false); passwordService.SetupSequence(o => o.GenerateCredentials(entity)).Returns(entity); mailService.SetupSequence(o => o.SendMessage( It.IsAny<System.Collections.Generic.List<string>>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>())) .Returns(true); LoginService service = new LoginService( repository.Object, passwordService.Object, mailService.Object, loggerService.Object); entity = service.RegisterUser(entity); Assert.IsNotNull(entity); }
public void SignIn_WrongCredentails_False() { Mock<IUserEntityRepository> repository = new Mock<IUserEntityRepository>(); Mock<IPasswordService> passwordService = new Mock<IPasswordService>(); Mock<IMailService> mailService = new Mock<IMailService>(); Mock<ILoggerService> loggerService = new Mock<ILoggerService>(); string Role; Guid ID; repository.Setup(o => o.Authenticate(It.IsAny<string>(), It.IsAny<string>(), out Role, out ID)).Returns(false); repository.Setup(o => o.Update(It.IsAny<UserEntity>(), false)); UserEntity user = new UserEntity(); user.ID = Guid.NewGuid(); user.FirstName = "Test"; repository.Setup(o => o.GetByEmail(It.IsAny<string>())).Returns(user); LoginService service = new LoginService( repository.Object, passwordService.Object, mailService.Object, loggerService.Object); bool flag = service.SignIn("*****@*****.**", "123", out Role, out ID); Assert.IsFalse(flag); }
public void ForgotPassword_null_False() { Mock<IUserEntityRepository> repository = new Mock<IUserEntityRepository>(); Mock<IPasswordService> passwordService = new Mock<IPasswordService>(); Mock<IMailService> mailService = new Mock<IMailService>(); Mock<ILoggerService> loggerService = new Mock<ILoggerService>(); LoginService service = new LoginService( repository.Object, passwordService.Object, mailService.Object, loggerService.Object); bool flag = service.ForgotPassword(null); Assert.IsFalse(flag); }
public AccountController() { _userContext = new UserContext(); _userRepository = new UserRepository(_userContext); _loginService = new LoginService(_userRepository); }
public AuthenticationController(UserService<SigmaUser> userService, LoginService<SigmaUser> loginService, IEmailService emailService) { UserService = userService; LoginService = loginService; EmailService = emailService; }
// This function will be called when scene loaded: void Start() { //init components viewByName = new Hashtable (); loginService = (LoginService)gameObject.AddComponent("LoginService"); registrationService = (RegistrationService)gameObject.AddComponent("RegistrationService"); loginView = (LoginView)gameObject.AddComponent("LoginView"); registrationView = (RegistrationView)gameObject.AddComponent("RegistrationView"); // Setup of login view: loginView.guiSkin = guiSkin; loginView.header1Style = header1Style; loginView.header2Style = header2Style; loginView.header2ErrorStyle = header2ErrorStyle; loginView.formFieldStyle = formFieldStyle; // Handler of registration button click: loginView.registrationHandler = delegate(){ // Clear reistration fields: registrationView.data.clear(); // Set active view to registration: activeViewName = RegistrationView.NAME; }; // Setup of login view: registrationView.guiSkin = guiSkin; registrationView.header2Style = header2Style; registrationView.formFieldStyle = formFieldStyle; registrationView.errorMessageStyle = errorMessageStyle; // Handler of cancel button click: registrationView.cancelHandler = delegate() { // Clear reistration fields: loginView.data.clear(); // Set active view to registration: activeViewName = LoginView.NAME; }; viewByName = new Hashtable(); // Adding views to views by name map: viewByName[LoginView.NAME] = loginView; viewByName[RegistrationView.NAME] = registrationView; loginView.loginHandler = delegate() { blockUI = true; // Sending login request: loginService.sendLoginData(loginView.data, loginResponseHandler); }; // Handler of Register button: registrationView.registrationHandler = delegate() { blockUI = true; // Sending registration request: registrationService.sendRegistrationData(registrationView.data, registrationResponseHandler); }; }
public void SignIn_NullPassword_ReturnFalse() { Mock<IUserEntityRepository> repository = new Mock<IUserEntityRepository>(); Mock<IPasswordService> passwordService = new Mock<IPasswordService>(); Mock<IMailService> mailService = new Mock<IMailService>(); Mock<ILoggerService> loggerService = new Mock<ILoggerService>(); string Role; Guid ID; repository.Setup(o => o.Authenticate(It.IsAny<string>(), It.IsAny<string>(), out Role, out ID)).Returns(true); LoginService service = new LoginService( repository.Object, passwordService.Object, mailService.Object, loggerService.Object); bool flag = service.SignIn("*****@*****.**", null, out Role, out ID); Assert.IsFalse(flag); }
public LoginService getLoginService() { if (loginService == null) { loginService = new LoginServiceImpl(); } return loginService; }