Exemplo n.º 1
0
        public ActionResult Login(LoginAccount loginModel)
        {
            if (ModelState.IsValid)
            {
                // Create an instance of the object model
                using (BlogDBEntities1 _entities = new BlogDBEntities1())
                {
                    /*var userDetails = (from e in _entities.RegisterDataEntities
                     *                 where e.UserName == loginModel.UserName &&
                     *                 e.Password == loginModel.Password
                     *                 select e);*/
                    var userDetails = _entities.RegisterDataEntities.Where(a => a.UserName.Equals(loginModel.UserName) && a.Password.Equals(loginModel.Password)).FirstOrDefault();

                    if (userDetails != null)
                    {
                        return(View("Success"));
                    }
                    else
                    {
                        Console.Write("Invalid User");
                    }
                }
            }

            Console.Write("Invalid User");
            return(View());
        }
Exemplo n.º 2
0
        public async Task <IActionResult> LoginAsync(LoginAccount command)
        {
            if (!ModelState.IsValid)
            {
                return(View("Login", command));
            }

            try
            {
                var account = await _accountService.LoginAsync(command);

                HttpContext.Session.SetString("Id", account.Id.ToString());
                HttpContext.Session.SetString("Login", account.Login);
                HttpContext.Session.SetString("Email", account.Email);
                HttpContext.Session.SetString("Role", account.Role);
                await HttpContext.Session.CommitAsync();

                ViewBag.ShowSuccess    = true;
                ViewBag.SuccessMessage = "Zalogowano pomyślnie";

                return(View("Login"));
            }
            catch (Exception)
            {
                ViewBag.ShowError    = true;
                ViewBag.ErrorMessage = "Coś poszło nie tak.";

                return(View("Login"));
            }
        }
Exemplo n.º 3
0
 public IActionResult Login([Bind("accountName, passWord")] LoginAccount requestAccount, string returnUrl)
 {
     if (ModelState.IsValid)
     {
         var account = _context.Accounts.FirstOrDefault(p => p.accountName == requestAccount.accountName && p.passWord == Utility.CreateMD5(requestAccount.passWord) && p.isActived == true);
         if (account != null)
         {
             HttpContext.Session.SetString("AccountName", account.accountName);
             HttpContext.Session.SetString("TypeAccount", Convert.ToString(account.typeAccount));
             if (!string.IsNullOrEmpty(returnUrl))
             {
                 returnUrl = System.Net.WebUtility.UrlDecode(returnUrl);
                 if (!returnUrl.Contains("Login") && !returnUrl.Contains("SignUp"))
                 {
                     return(Redirect(returnUrl));
                 }
             }
             return(RedirectToAction("Index", "Home"));
         }
         else
         {
             ModelState.AddModelError("", "Tên đăng nhập hoặc mật khẩu không hợp lệ !");
             return(View());
         }
     }
     return(View());
 }
        async Task LoginAsync(LoginAccount account)
        {
            switch (account)
            {
            case LoginAccount.Facebook:
                await viewModel.ExecuteLoginFacebookCommandAsync();

                break;

            case LoginAccount.Microsoft:
                await viewModel.ExecuteLoginMicrosoftCommandAsync();

                break;

            case LoginAccount.Twitter:
                await viewModel.ExecuteLoginTwitterCommandAsync();

                break;
            }

            if (viewModel.IsLoggedIn)
            {
                //When the first screen of the app is launched after user has logged in, initialize the processor that manages connection to OBD Device and to the IOT Hub
                Services.OBDDataProcessor.GetProcessor().Initialize(ViewModel.ViewModelBase.StoreManager);

                NavigateToTabs();
            }
        }
Exemplo n.º 5
0
        public ActionResult Login(LoginAdmin admin)
        {
            if (ModelState.IsValid)
            {
                var dao    = new AccountDAO();
                var result = dao.Login(admin.Username, Encryptor.MD5Hash(admin.Password), admin.GroupID);
                if (result == 1)
                {
                    var account        = dao.GetByID(admin.Username);
                    var accountSession = new LoginAccount();
                    accountSession.Username  = account.username;
                    accountSession.IdAccount = account.id;
                    Session.Add(SessionConstant.USER_SESSION, accountSession);

                    return(RedirectToAction("Index", "Home"));
                }
                else if (result == 0)
                {
                    ModelState.AddModelError("", "Tai khoan nay khong ton tai!!");
                }
                else if (result == -1)
                {
                    ModelState.AddModelError("", "Tai khoan nay dang bi khoa!!");
                }
                else if (result == -2)
                {
                    ModelState.AddModelError("", "Sai mat khau!!");
                }
                else
                {
                    ModelState.AddModelError("", "Dang nhap khong dung!!");
                }
            }
            return(View("Index"));
        }
Exemplo n.º 6
0
        public ActionResult LoginAccount(Employer employer, Seeker seeker, LoginAccount login)
        {
            string seekerName  = loginManager.GetSeekerName(login);
            int    seekerId    = loginManager.GetSeekerID(login);
            string seekerEmail = login.Email;

            string employerName  = loginManager.GetEmployerCompanyName(login);
            int    employerId    = loginManager.GetEmployerCompanyID(login);
            string employerEmail = login.Email;

            if (!seekerName.Equals(""))
            {
                Session["user"] = new Seeker()
                {
                    DisplayName = seeker.Name, Name = seekerName, SeekerID = seekerId, Email = seekerEmail
                };
                return(RedirectToAction("Index", "Home"));
            }
            else if (!employerName.Equals(""))
            {
                Session["user"] = new Employer()
                {
                    DisplayName = employer.CompanyName, CompanyName = employerName, EmployerID = employerId, ContactPersonEmail = employerEmail
                };
                return(RedirectToAction("Index", "Home"));
            }
            else
            {
                string message = "Email or Password is Incorrect";
                ViewBag.message = message;
            }

            return(View());
        }
Exemplo n.º 7
0
        public async Task <string> LoginAsync(LoginAccount command)
        {
            var loginOrEmailHash = _hashManager.CalculateDataHash(command.LoginOrEmail);

            var user = await _context.Users.GetByEmail(loginOrEmailHash)
                       .Select(x => new { x.PasswordHash, x.Salt, x.Role, x.Id, x.IsActive })
                       .AsNoTracking().SingleOrDefaultAsync();

            if (user == null)
            {
                user = await _context.Users.GetByLogin(loginOrEmailHash)
                       .Select(x => new { x.PasswordHash, x.Salt, x.Role, x.Id, x.IsActive })
                       .AsNoTracking().SingleOrDefaultAsync();
            }

            if (user == null)
            {
                throw new CorruptedOperationException("Invalid credentials.");
            }

            if (_hashManager.VerifyPasswordHash(command.Password, user.PasswordHash, user.Salt) == false)
            {
                throw new CorruptedOperationException("Invalid credentials.");
            }

            return(await _jwtHandler.CreateTokenAsync(user.Id, user.Role));
        }
Exemplo n.º 8
0
        /// <summary>
        /// 在指定的MFiles服务器中添加登陆账户
        /// </summary>
        /// <param name="user">用户对象</param>
        /// <param name="server">MFiles Server对象 </param>
        internal void CreateMFilesLoginAccount(User user, VaultServer server,
                                               MFLoginAccountType accountType, MFLicenseType licenseType)
        {
            var app = MFServerUtility.ConnectToServer(server.AdminName, server.AdminPwd,
                                                      MFServerUtility.GetVaultServerLocalIp(server), server.ServerPort);

            try
            {
                var accountName = GetAccountName(user);
                var hasAccount  = MfUserUtils.HasLoginAccount(app, accountName);
                if (!hasAccount)
                {
                    var account  = new LoginAccount();
                    var fullName = user.FullName;
                    if (String.IsNullOrEmpty(fullName))
                    {
                        fullName = user.UserName;
                    }
                    account.Set(accountType, user.Domain, user.UserName,
                                MFLoginServerRole.MFLoginServerRoleLogIn, fullName, user.Email, licenseType);
                    app.LoginAccountOperations.AddLoginAccount(account);
                }
            }
            finally
            {
                app.Disconnect(); //todo 多线程时是否对其他会话有影响
            }
        }
Exemplo n.º 9
0
 public bool AuthenticateByOpenID(Session session, string openID, out LoginAccount loginAccount)
 {
     loginAccount = null;
     try
     {
         CriteriaOperator criteriaLoginAccount =
             CriteriaOperator.And(
                 new BinaryOperator("RowStatus", Utility.Constant.ROWSTATUS_ACTIVE),
                 new BinaryOperator("Email", openID)
                 );
         loginAccount = session.FindObject <LoginAccount>(criteriaLoginAccount);
         if (loginAccount != null)
         {
             if (loginAccount.PersonId.RowStatus.Equals(Utility.Constant.ROWSTATUS_ACTIVE))
             {
                 return(true);
             }
             else
             {
                 return(false);
             }
         }
         else
         {
             return(false);
         }
     }
     catch (Exception)
     {
         loginAccount = null;
         return(false);
     }
 }
Exemplo n.º 10
0
        public int GetSeekerID(LoginAccount login)
        {
            SqlConnection connection = new SqlConnection(connectionString);
            string        query      = "Select SeekerID from JobSeekersInfo where Email = @email";

            connection.Open();

            SqlCommand command = new SqlCommand(query, connection);


            command.Parameters.Add("email", SqlDbType.VarChar);
            command.Parameters["email"].Value = login.Email;

            command.CommandText = query;
            command.Connection  = connection;
            SqlDataReader reader = command.ExecuteReader();

            int id = 0;

            if (reader.Read())
            {
                id = Convert.ToInt32(reader["SeekerID"]);
            }
            return(id);
        }
        public async Task <IActionResult> Login(LoginAccount account, string returnTo)
        {
            if (ModelState.IsValid)
            {
                var result = await _signInManager.PasswordSignInAsync(
                    userName : account.UserName,
                    password : account.Password,
                    isPersistent : account.RememberMe,
                    lockoutOnFailure : false);


                if (result.Succeeded)
                {
                    return(RedirectToLocal(returnTo));
                }

                if (result.RequiresTwoFactor)
                {
                    return(RedirectToRoute("GetSendCode", new { returnTo, rememberMe = account.RememberMe }));
                }

                if (result.IsLockedOut)
                {
                    return(View("LockOut"));
                }

                if (result.IsNotAllowed)
                {
                    if (_userManager.Options.SignIn.RequireConfirmedPhoneNumber)
                    {
                        if (!await _userManager.IsPhoneNumberConfirmedAsync(new User {
                            UserName = account.UserName
                        }))
                        {
                            ModelState.AddModelError(string.Empty, "شماره تلفن شما تایید نشده است.");

                            return(View(account));
                        }
                    }


                    if (_userManager.Options.SignIn.RequireConfirmedEmail)
                    {
                        if (!await _userManager.IsEmailConfirmedAsync(new User {
                            UserName = account.UserName
                        }))
                        {
                            ModelState.AddModelError(string.Empty, "آدرس اییل شما تایید نشده است.");

                            return(View(account));
                        }
                    }
                }
            }


            ModelState.AddModelError(string.Empty, "Invalid username or password");

            return(View(account));
        }
Exemplo n.º 12
0
        public string EmployerGetName(LoginAccount login)
        {
            SqlConnection connection = new SqlConnection(connectionString);
            string        query      = "Select CompanyName from EmployersInfo where ContactPersonEmail = @contactPersonEmail";

            connection.Open();

            SqlCommand command = new SqlCommand(query, connection);


            command.Parameters.Add("contactPersonEmail", SqlDbType.VarChar);
            command.Parameters["contactPersonEmail"].Value = login.Email;

            command.CommandText = query;
            command.Connection  = connection;
            SqlDataReader reader = command.ExecuteReader();

            string name = "";

            if (reader.Read())
            {
                name = reader["CompanyName"].ToString();
            }
            return(name);
        }
Exemplo n.º 13
0
 public LoginAccountTests()
 {
     validator = new LoginAccountValidation();
     command   = new LoginAccount(
         "testUser",
         "123456");
 }
Exemplo n.º 14
0
        public bool IsEmployerEmailPasswordExist(LoginAccount login)
        {
            SqlConnection connection = new SqlConnection(connectionString);
            string        query      = "Select * from EmployersInfo where ContactPersonEmail =(@contactPersonEmail) and Password =(@password)";

            connection.Open();

            SqlCommand command = new SqlCommand(query, connection);



            command.Parameters.Add("contactPersonEmail", SqlDbType.VarChar);
            command.Parameters["contactPersonEmail"].Value = login.Email;

            command.Parameters.Add("password", SqlDbType.VarChar);
            command.Parameters["password"].Value = login.Password;

            command.CommandText = query;
            command.Connection  = connection;
            SqlDataReader reader = command.ExecuteReader();

            if (reader.Read())
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
        public PartialViewResult CheckLogin(LoginAccount l)
        {
            if (ModelState.IsValid)
            {
                var u = Auth.CheckAccount(l);
                if (u != null)
                {
                    if (u.isActive)
                    {
                        HttpCookie authCookie = new HttpCookie("UID", u.UID);
                        authCookie.Expires = DateTime.Now.AddDays(60);
                        Response.Cookies.Add(authCookie);
                        Response.Flush();
                    }
                    else
                    {
                        Response.StatusCode = 201;
                        ModelState.AddModelError("", "Account has not been activated !");
                    }
                }
                else
                {
                    Response.StatusCode = 201;
                    ModelState.AddModelError("", "Account or password incorrect !");
                }

                return(PartialView("LoginForm"));
            }
            Response.StatusCode = 201;
            return(PartialView("LoginForm"));
        }
Exemplo n.º 16
0
 public ActionResult Login(LoginModel model)
 {
     if (ModelState.IsValid)
     {
         var dao    = new AccountDAO();
         var result = dao.LoginUser(model.UserName, Encryptor.MD5Hash(model.Password), model.Roll);
         if (result == 1)
         {
             var user        = dao.GetByID(model.UserName);
             var userSession = new LoginAccount();
             userSession.Username  = user.username;
             userSession.IdAccount = user.id;
             Session.Add(SessionConstant.USER_SESSION, userSession);
             return(RedirectToAction("Index", "Home"));
         }
         else if (result == 0)
         {
             ModelState.AddModelError("", "Tài khoản không tồn tại.");
         }
         else if (result == -1)
         {
             ModelState.AddModelError("", "Tài khoản đang bị khoá.");
         }
         else if (result == -2)
         {
             ModelState.AddModelError("", "Mật khẩu không đúng.");
         }
         else
         {
             ModelState.AddModelError("", "đăng nhập không đúng.");
         }
     }
     return(View(model));
 }
        public IActionResult Login(LoginAccount submission)
        {
            // Checks to see if all the data fields were completed
            if (ModelState.IsValid)
            {
                // If there are no form errors, query the DB for the Account's
                // Email in the DB to see if it exists

                var loginAccount = dbContext.Accounts.FirstOrDefault(a => a.Email == submission.Email);

                // If Account email doesn't exist, throw a form field error and
                // return the Index view

                if (loginAccount == null)
                {
                    ModelState.AddModelError("Password", "Invalid Email/Password!");
                    return(View("Index"));
                }

                // Else attempt to verify the password
                else
                {
                    // Creates a password hasher object using Identity
                    var hasher = new PasswordHasher <LoginAccount>();

                    // Query the DB to verify password against the object queried from the DB
                    var result = hasher.VerifyHashedPassword(submission, loginAccount.Password, submission.Password);

                    // Result compared to 0 for failure
                    if (result == 0)
                    {
                        // Failure throws a password error and returns the Index View
                        ModelState.AddModelError("Password", "Invalid Email/Password!");
                        return(View("Index"));
                    }

                    // Else creates 'Logged In' status, with security validation.
                    // Each route can now check to see if the User is logged in using
                    // session data to validate a query to the DB. If the email does
                    // not match the email for the user id, then session will be cleared.
                    // *NOTE* this can eventually replaced with Indentity in future projects!
                    else
                    {
                        HttpContext.Session.SetString("LoggedIn", "true");
                        HttpContext.Session.SetInt32("AccountId", loginAccount.AccountId);
                        HttpContext.Session.SetString("Email", loginAccount.Email);

                        // Redirects to the Messages Index, now "Logged In"
                        return(RedirectToAction("Index", "Products"));
                    }
                }
            }

            // Else returns the Accounts Index
            else
            {
                return(View("Index"));
            }
        }
        public LoginAccount UpdateUser(LoginAccount user, Roles[] roles)
        {
            var roles_parsed = string.Join(",", roles.Select(VeracodeEnumConverter.Convert).ToArray());
            var xml          = _wrapper.UpdateUser(user.username, user.first_name,
                                                   user.last_name, user.email_address, roles_parsed, user.teams);

            return(XmlParseHelper.Parse <userinfo>(xml).login_account);
        }
Exemplo n.º 19
0
 public IEnumerable <IEvent> On(LoginAccount command)
 {
     if (!PasswordHelper.IsPasswordMatch(command.Password, Password))
     {
         throw new ArgumentException("password not correct");
     }
     yield return(new AccountLoggedIn(command.ID));
 }
Exemplo n.º 20
0
        public async Task <IActionResult> LoginUserAsync([FromBody] LoginAccount command)
        {
            var token = await _userService.LoginAsync(command);

            var tokenDto = _mapper.Map <JwtDto>(token);

            return(Ok(tokenDto));
        }
Exemplo n.º 21
0
        public bool PersonEditing_PreTransitionCRUD(string transition)
        {
            switch (transition)
            {
            case "Save":
                if (!ASPxEdit.AreEditorsValid(popup_PersonCreate))
                {
                    return(false);
                }
                Person person = session.GetObjectByKey <Person>(PersonId);
                {
                    person.Code      = txt_Code.Text;
                    person.Name      = txt_Name.Text;
                    person.RowStatus = Convert.ToInt16(Combo_RowStatus.SelectedItem.Value);
                };
                person.Save();

                var statementLoginAccounts = from la in person.LoginAccounts
                                             where la.RowStatus > 0 &&
                                             la.PersonId == person
                                             select la.LoginAccountId;

                foreach (TMPLoginAccount tmpAccount in Temp_LoginAccount)
                {
                    LoginAccount account;
                    if (statementLoginAccounts.Contains(tmpAccount.LoginAccountId))
                    {
                        account           = session.GetObjectByKey <LoginAccount>(tmpAccount.LoginAccountId);
                        account.Email     = tmpAccount.Email;
                        account.RowStatus = Utility.Constant.ROWSTATUS_ACTIVE;
                        account.Save();
                    }
                    else
                    {
                        account = new LoginAccount(session);
                        account.LoginAccountId       = Guid.NewGuid();
                        account.Email                = tmpAccount.Email;
                        account.RowStatus            = Utility.Constant.ROWSTATUS_ACTIVE;
                        account.RowCreationTimeStamp = DateTime.Now;
                        account.PersonId             = person;
                        account.Save();
                    }
                }

                // update Department
                List <TreeListNode> nodes = ASPxTreeList_OfDepartment.GetSelectedNodes();
                List <NAS.DAL.Nomenclature.Organization.Department> departmentList = new List <NAS.DAL.Nomenclature.Organization.Department>();
                foreach (TreeListNode n in nodes)
                {
                    NAS.DAL.Nomenclature.Organization.Department d = (NAS.DAL.Nomenclature.Organization.Department)n.DataItem;
                    departmentList.Add(d);
                }
                DepartmentBO bo = new DepartmentBO();
                bo.updatePerson(session, departmentList, PersonId, person.Code, person.Name, person.RowStatus);
                return(true);
            }
            return(false);
        }
Exemplo n.º 22
0
        public ActionResult Index(LoginAccount login)
        {
            byte[] s = System.Text.ASCIIEncoding.ASCII.GetBytes(login.Password);

            string encrypted = Convert.ToBase64String(s);



            var Model = _context.Account.Any(x => x.Email == login.Email && x.Password == encrypted);



            if (Model)
            {
                var model = _context.Account.Where(x => x.Email == login.Email);



                var test = model.Select(x => x.Active).FirstOrDefault();



                int MyId = model.Select(x => x.Id).FirstOrDefault();


                var FriendBase = _context.Friends.Where(x => x.FirstUser == MyId).ToList();

                List <Account> friends = new List <Account>();



                foreach (var item in FriendBase)
                {
                    int FriendId = item.SecondUser;



                    var FriendModel = _context.Account.Where(x => x.Id == FriendId);



                    friends.Add(FriendModel.FirstOrDefault());


                    ViewBag.Friends = friends;
                }

                return(View("Main"));
            }
            else
            {
                ViewBag.valid     = "Podałeś nieprawdziwy Email";
                ViewBag.validPass = "******";

                return(View());
            }
        }
Exemplo n.º 23
0
    public static async Task CustomLoginAsync(this MobileServiceClient client, LoginAccount account)
    {
        var jsonResponse = await client.InvokeApiAsync("/.auth/login/custom", JObject.FromObject(account), HttpMethod.Post, null);

        //after successfully logined, construct the MobileServiceUser object with MobileServiceAuthenticationToken
        client.CurrentUser = new MobileServiceUser(jsonResponse["user"]["userId"].ToString());
        client.CurrentUser.MobileServiceAuthenticationToken = jsonResponse.Value <string>("authenticationToken");
        //retrieve custom response parameters
        string customUserName = jsonResponse["user"]["userName"].ToString();
    }
 public LoginAccountHandlerTests()
 {
     fakeAccountRepository = new Mock <IAccountRepository>();
     command = new LoginAccount(
         "testUser",
         "123456");
     signInResultSuccess           = SignInResult.Success;
     signInResultTwoFactorRequired = SignInResult.TwoFactorRequired;
     signInResultLockedOut         = SignInResult.LockedOut;
     signInResultFailure           = SignInResult.Failed;
 }
Exemplo n.º 25
0
        public IActionResult RequestToken([FromBody] LoginAccount request)
        {
            var result = Helpers.GetToken(request, _configuration);

            if (!string.IsNullOrEmpty(result))
            {
                return(Ok(result));
            }

            return(BadRequest("Could not verify username and password"));
        }
Exemplo n.º 26
0
        public string GetEmployerCompanyName(LoginAccount login)
        {
            bool isExist = loginGetway.IsEmployerEmailPasswordExist(login);

            string name = "";

            if (isExist)
            {
                name = loginGetway.EmployerGetName(login);
            }
            return(name);
        }
Exemplo n.º 27
0
        public int GetSeekerID(LoginAccount login)
        {
            bool isExist = loginGetway.IsSeekerEmailPasswordExist(login);

            int id = 0;

            if (isExist)
            {
                id = loginGetway.GetSeekerID(login);
            }
            return(id);
        }
Exemplo n.º 28
0
        public int GetEmployerCompanyID(LoginAccount login)
        {
            bool isExist = loginGetway.IsEmployerEmailPasswordExist(login);

            int id = 0;

            if (isExist)
            {
                id = loginGetway.GetEmployerID(login);
            }
            return(id);
        }
Exemplo n.º 29
0
        //Verify User&Pass
        public static bool VerifyUser(string Username, string Password)
        {
            DataTable    Data         = new DataTable();
            LoginAccount loginAccount = new LoginAccount();

            using (IQueryAdapter dbClient = LoginServer.dbManager.getQueryreactor())
            {
                string GetAccountQuery = "SELECT * FROM accounts WHERE Username='******' && Password='******';";
                dbClient.setQuery(GetAccountQuery);
                Data = dbClient.getTable();

                if (Data != null)
                {
                    foreach (DataRow Row in Data.Rows)
                    {
                        loginAccount = new LoginAccount()
                        {
                            AccountId     = uint.Parse(Row["id"].ToString()),
                            Username      = Row["username"].ToString(),
                            Password      = Row["password"].ToString(),
                            Email         = Row["email"].ToString(),
                            AccessLevel   = uint.Parse(Row["accesslevel"].ToString()),
                            Membership    = Row["membership"].ToString(),
                            IsGM          = Convert.ToBoolean(int.Parse(Row["isgm"].ToString())),
                            LastOnlineUtc = Convert.ToInt64((long.Parse(Row["lastonlineutc"].ToString()))),
                            Coins         = Convert.ToUInt32((Row["coins"].ToString())),
                            Ip            = Row["ip"].ToString(),
                            Settings      = Row["settings"].ToString(),
                            IsOnline      = Convert.ToBoolean(int.Parse(Row["isonline"].ToString())),
                            IsBanned      = Convert.ToBoolean(int.Parse(Row["isbanned"].ToString())),
                            UnBanDate     = Convert.ToInt64((long.Parse(Row["unbandate"].ToString()))),
                            RegisterDate  = Convert.ToInt64((long.Parse(Row["registerdate"].ToString()))),
                        };
                    }

                    if (loginAccount.Username != null)
                    {
                        if (loginAccount.Username != Username)
                        {
                            Logger.WriteLine(LogState.Error, "Account.Username missmatch!");
                            return(false);
                        }
                        if (loginAccount.Username == Username && loginAccount.Password == Password)
                        {
                            Logger.WriteLine(LogState.Info, "Verify ok!");
                            return(true);
                        }
                    }
                }
            }
            Logger.WriteLine(LogState.Error, "Verify failed!");
            return(false);
        }
Exemplo n.º 30
0
        public HttpResponseMessage Login([FromBody] LoginAccount user)
        {
            var           resp         = new HttpResponseMessage();
            LoginJsonView jsonreturned = new LoginJsonView();
            var           item         = new JsonTokenLogin();

            try
            {
                var entity = userRepository.FindUser(user.email, user.password);
                if (entity != null)
                {
                    string encodedUserCredentials =
                        Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes("user:password"));
                    string         userData = "username="******"&password="******"&grant_type=password";
                    HttpWebRequest request  = (HttpWebRequest)WebRequest.Create(Configurations.APITokenURL);
                    request.Accept      = "application/json";
                    request.Method      = "POST";
                    request.ContentType = "application/x-www-form-urlencoded";
                    request.Headers.Add("Authorization", "Bearer " + encodedUserCredentials);

                    StreamWriter requestWriter = new StreamWriter(request.GetRequestStream());
                    requestWriter.Write(userData);
                    requestWriter.Close();

                    var response = request.GetResponse() as HttpWebResponse;

                    string jsonString;
                    using (Stream stream = response.GetResponseStream())
                    {
                        StreamReader reader = new StreamReader(stream);
                        jsonString = reader.ReadToEnd();
                    }
                    JavaScriptSerializer js = new JavaScriptSerializer();
                    jsonreturned.token = new JsonTokenLogin();
                    jsonreturned.token = js.Deserialize <JsonTokenLogin>(jsonString);

                    jsonreturned.user = new UserView();
                    jsonreturned.user = Mapper.Map <User, UserView>(entity);

                    resp = Request.CreateResponse(HttpStatusCode.OK, jsonreturned);
                }
                else
                {
                    resp = Request.CreateErrorResponse(HttpStatusCode.NotFound, "The user Not found");
                }

                return(resp);
            }
            catch (Exception exp)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, exp));
            }
        }
Exemplo n.º 31
0
 void Login(LoginAccount account)
 {
     switch (account)
     {
         case LoginAccount.Facebook:
             viewModel.LoginFacebookCommand.Execute(null);
             break;
         case LoginAccount.Microsoft:
             viewModel.LoginMicrosoftCommand.Execute(null);
             break;
         case LoginAccount.Twitter:
             viewModel.LoginTwitterCommand.Execute(null);
             break;
     }
 }
        private TestObjects Setup()
        {
            var vObjects = new TestObjects();
            vObjects.HashProvider = new Mock<IHashProvider>();
            vObjects.HashProvider.Setup(t => t.Hash(cPassword)).Returns(cHash);
            vObjects.HashProvider.Setup(t => t.CheckHash(cPassword, cHash)).Returns(true);

            vObjects.DocumentStore = GetEmbeddedDatabase;

            var vNewAccount = new CreateAccount
                                  {
                                      Name = cName,
                                      Email = cEmail,
                                      Password = cPassword
                                  };
            var vAccountCommandFactory = new Mock<IAccountCommandFactory>();
            var vSendConfirmationCommand = new Mock<ISendConfirmationCommand>();
            vAccountCommandFactory
                .Setup(t => t.CreateSendConfirmationCommand(It.IsAny<Account>()))
                .Returns(vSendConfirmationCommand.Object);


            var vNewAccountCommand = new CreateAccountCommand(
                vObjects.DocumentStore,
                vObjects.HashProvider.Object, vAccountCommandFactory.Object, new CryptoRandomProvider(),
                vNewAccount);
            vNewAccountCommand.Execute();

            var vLogin = new LoginAccount
                             {
                                 Name = cName,
                                 Password = cPassword
                             };
            vObjects.GoodLoginAccountCommand = new LoginAccountCommand(
                vObjects.DocumentStore,
                vObjects.HashProvider.Object,
                vLogin);
            return vObjects;
        }
Exemplo n.º 33
0
        async Task LoginAsync(LoginAccount account)
        {
            switch (account)
            {
                case LoginAccount.Facebook:
                    await viewModel.ExecuteLoginFacebookCommandAsync();
                    break;
                case LoginAccount.Microsoft:
                    await viewModel.ExecuteLoginMicrosoftCommandAsync();
                    break;
                case LoginAccount.Twitter:
                    await viewModel.ExecuteLoginTwitterCommandAsync();
                    break;
            }

            if (viewModel.IsLoggedIn)
            {
                //When the first screen of the app is launched after user has logged in, initialize the processor that manages connection to OBD Device and to the IOT Hub
                Services.OBDDataProcessor.GetProcessor().Initialize(ViewModel.ViewModelBase.StoreManager);

                NavigateToTabs();
            }
        }
 public async void LoginReturnsFalseWithBadLoginInfo(string tName, string tPassword)
 {
     var vObjects = Setup();
     var vLogin = new LoginAccount
                      {
                          Name = tName,
                          Password = tPassword,
                      };
     var vBadLoginAccountCommand = new LoginAccountCommand(
         vObjects.DocumentStore,
         vObjects.HashProvider.Object,
         vLogin);
     var vResult = await vBadLoginAccountCommand.Execute();
     Assert.IsFalse(vResult);
 }