private bool SaveBasicDetails(tbl_Std_Admission_Details basicdetails)
        {
            bool result = false;

            using (OnlineStudentAdmissionEntities1 _entity = new OnlineStudentAdmissionEntities1())
            {
                int       userid = Convert.ToInt32(Session["ID"].ToString());
                UserLogIn _user  = _entity.UserLogIn.Where(x => x.Id == userid).Select(x => x).FirstOrDefault();
                basicdetails.Username = _user.Username;
                basicdetails.Password = _user.Password;
                if (Session["Admission_id"] == null)
                {
                    _entity.tbl_Std_Admission_Details.Add(basicdetails);
                    _entity.SaveChanges();
                    result = true;
                    tbl_Std_Admission_Details _student = _entity.tbl_Std_Admission_Details.Where(x => x.CreatedBy == userid).Select(x => x).FirstOrDefault();
                    _student.Admission_Id   = basicdetails.Admission_Id;
                    Session["Admission_Id"] = _student.Admission_Id;
                }
                else
                {
                    tbl_Std_Admission_Details _student = _entity.tbl_Std_Admission_Details.Where(x => x.CreatedBy == userid).Select(x => x).FirstOrDefault();
                    _student.Name     = basicdetails.Name;
                    _student.Mobile   = basicdetails.Mobile;
                    _student.Gender   = basicdetails.Gender;
                    _student.Category = basicdetails.Category;
                    _entity.SaveChanges();
                    result = true;
                }
            }
            return(result);
        }
示例#2
0
        public async Task <ActionResult> Login(UserLogIn useLogIn)
        {
            // find the user
            var user = await _context
                       .Users
                       .FirstOrDefaultAsync(user => user.Email.ToLower() == useLogIn.Email.ToLower());

            if (user == null)
            {
                return(BadRequest("User does not exists"));
            }
            // validate the password
            var results = new PasswordHasher <User>().VerifyHashedPassword(user, user.HashedPassword, useLogIn.Password);

            if (results == PasswordVerificationResult.Success)
            {
                // create the token
                user.HashedPassword = null;
                return(Ok(new { Token = CreateJWT(user), user = user }));
            }
            else
            {
                return(BadRequest("Incorrect password!"));
            }
        }
示例#3
0
        /// <summary>
        /// Logs an user in the application
        /// </summary>
        /// <param name="user">The info to log</param>
        /// See <see cref="Areas.Identity.Models.UserLogIn"/> to see the param structure
        /// <returns>The IActionResult of the login action</returns>
        /// See <see cref="Areas.Identity.Models.UserSession"/> to see the return structure
        public IActionResult logIn([FromBody] UserLogIn user)
        {
            var userExist = this._context.User.Where(u => u.email == user.email);

            if (userExist.Count() != 1 || !PasswordHasher.areEquals(user.password, userExist.First().password))
            {
                return(BadRequest(new { error = "WrongEmailOrPassword" }));
            }
            User loggedUser = userExist.First();

            if (loggedUser.tokenValidation != null)
            {
                return(BadRequest(new { error = "NotValidatedYet" }));
            }
            if (!loggedUser.open)
            {
                return(BadRequest(new { error = "YoureBanned" }));
            }
            if (loggedUser.dateDeleted != null)
            {
                ResetDelete.reset(loggedUser, _context);
                Home.Util.GroupNew.launch(loggedUser, null, null, Home.Models.TypeGroupNew.WELCOMEBACK, false, _context);
            }

            UserSession session = MakeUserSession.getUserSession(_context, userExist.First(), user.provider);

            if (session == null)
            {
                return(StatusCode(500));
            }

            return(Ok(session));
        }
示例#4
0
        public async Task <IActionResult> Index(UserLogIn userInfo, string returnUrl = null)
        {
            //kontroller användarnamn
            bool userOk = checkUser(userInfo);

            if (userOk == true)
            {
                // Allt stämmer, logga in användaren
                var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
                identity.AddClaim(new Claim(ClaimTypes.Name, userInfo.Username));

                await HttpContext.SignInAsync(
                    CookieAuthenticationDefaults.AuthenticationScheme,
                    new ClaimsPrincipal(identity));


                if (returnUrl != null)
                {
                    return(Redirect(returnUrl));
                }
                else
                {
                    return(RedirectToAction("Index", "Home"));
                }
            }

            ViewBag.ErrorMessage = "Log in failed";

            return(View());
        }
        public async Task <IActionResult> Edit(int id, [Bind("userId,name,password,Email,phnNumber")] UserLogIn userLogIn)
        {
            if (id != userLogIn.userId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(userLogIn);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!UserLogInExists(userLogIn.userId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(userLogIn));
        }
示例#6
0
        public IActionResult LogIn(UserLogIn user)
        {
            UserCreator UserFactory = new UserCreator();
            string      message     = "";

            if (ModelState.IsValid)
            {
                UserDBService UserDB      = UserDBService.GetInstance;
                User          CurrentUser = UserFactory.LogInUser(user);
                if (CurrentUser != null)
                {
                    // Debugging Purposes
                    //TempData["User"] = CurrentUser.UserName;
                    //TempData["Password"] = CurrentUser.Password;

                    //SetCookie("User", CurrentUser.UserName, 2);
                    //SetCookie("Password", CurrentUser.UserName, 2);

                    HttpContext.Session.SetString(CookieKeys.USERNAME, CurrentUser.UserName);
                    HttpContext.Session.SetString(CookieKeys.PASSWORD, CurrentUser.Password);

                    return(RedirectToAction("Overview", "Home"));
                    //return Content(CurrentUser.ToString());
                }
                else
                {
                    message = "Failed to log in. Your information does not match any record in our database.\nIf your information was correct contact your admin.\n\nPlease try again";
                }
            }
            else
            {
                message = "Failed to log in. Unformatted information .\n\nPlease try again";
            }
            return(RedirectToAction("Messages", "Home", new { Message = message }));
        }
示例#7
0
        public async Task <ActionResult> Login(UserLogIn model, string returnUrl)
        {
            UserSecurity hostList;

            hostList = _repository.LogIn(model.Login, model.Password);

            if (hostList == null)
            {
                return(View(model));
            }

            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            //var result = await SignInManager.PasswordSignInAsync(model.Login, model.Password, model.RememberMe, shouldLockout: false);
            //var result = await SignInManager.PasswordSignInAsync(model.Login, model.Password, false, shouldLockout: false);

            return(RedirectToLocal("~/Home/Index"));

            /*  switch (result)
             * {
             *    case SignInStatus.Success:
             *        return RedirectToLocal(returnUrl);
             *    case SignInStatus.LockedOut:
             *        return View("Lockout");
             *    //case SignInStatus.RequiresVerification:
             *    //    return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
             *    case SignInStatus.Failure:
             *    default:
             *        ModelState.AddModelError("", "Invalid login attempt.");
             *        return View(model);
             * }*/
        }
        private async Task <UserToken> BuildToken(UserLogIn model)
        {
            var claims = new List <Claim>()
            {
                new Claim(ClaimTypes.Name, model.Email),
                new Claim(ClaimTypes.Email, model.Email),
                new Claim("myvalue", "whatever I want")
            };

            var identityUser = await _userManager.FindByEmailAsync(model.Email);

            var claimsDB = await _userManager.GetClaimsAsync(identityUser);

            claims.AddRange(claimsDB);

            var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:key"]));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var expiration = DateTime.UtcNow.AddYears(1);

            JwtSecurityToken token = new JwtSecurityToken(
                issuer: null,
                audience: null,
                claims: claims,
                expires: expiration,
                signingCredentials: creds);

            return(new UserToken()
            {
                Token = new JwtSecurityTokenHandler().WriteToken(token),
                Expiration = expiration
            });
        }
        public ActionResult LogIn(UserLogIn user, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                using (var context = new SingularityDBContext())
                {
                    var username = user.Username;
                    var password = user.Password;

                    var userIsValid = context.UserLogIns.Any(dbUserLogIns => dbUserLogIns.Username == username &&
                                                             dbUserLogIns.Password == password);

                    if (userIsValid)
                    {
                        FormsAuthentication.SetAuthCookie(user.Username, false);

                        if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") &&
                            !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                        {
                            return(Redirect(returnUrl));
                        }
                        else
                        {
                            return(RedirectToAction("Index", "Home"));
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "username or password is incorrect");
                    }
                }
            }

            return(View(user));
        }
示例#10
0
        public ActionResult DeleteConfirmed(string id)
        {
            UserLogIn userLogIn = db.UserLogIns.Find(id);

            db.UserLogIns.Remove(userLogIn);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
示例#11
0
        public void UserLogin_Creational_SetsCreatedDateAndLastActivityDate()
        {
            //arrange
            var userLogin = new UserLogIn();

            //assert
            Assert.AreEqual(userLogin.CreatedDate.ToString("dd.MM.yyyy hh:mm"), DateTime.Now.ToString("dd.MM.yyyy hh:mm"));
            Assert.AreEqual(userLogin.LastActivityDate.ToString("dd.MM.yyyy hh:mm"), DateTime.Now.ToString("dd.MM.yyyy hh:mm"));
        }
示例#12
0
 public ActionResult Edit([Bind(Include = "Email,Password,ConfirmPassword")] UserLogIn userLogIn)
 {
     if (ModelState.IsValid)
     {
         db.Entry(userLogIn).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(userLogIn));
 }
示例#13
0
        public async Task <UserToken> Login(UserLogIn userLogIn)
        {
            var httpResponse = await httpService.Post <UserLogIn, UserToken>($"{baseURL}/login", userLogIn);

            if (!httpResponse.Success)
            {
                throw new ApplicationException(await httpResponse.GetBody());
            }

            return(httpResponse.Response);
        }
示例#14
0
        public async Task <bool> LogInUser(Guid productId, string email, string password)
        {
            UserLogIn operation = new UserLogIn(_authorityContext, productId, email, password);

            if (!await operation.Do())
            {
                return(false);
            }

            return(true);
        }
示例#15
0
        public void UserLogin_IsUserLoggedIn()
        {
            //arrange
            var userLogin = new UserLogIn();

            //act
            var loggedIn = userLogin.IsUserLoggedIn();

            //assert
            Assert.IsTrue(loggedIn);
        }
示例#16
0
 private bool checkUser(UserLogIn userInfo)
 {   // ändra t databas ist för hårdkodat
     if (userInfo.Username == "admin" && userInfo.Password == "admin")
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
示例#17
0
        private UserLogIn AuthenticateUser(UserLogIn login)
        {
            //UserLogIn user = null;

            #region unnecessary

            //Validate the User Credentials

            //if (login.Username == "Jignesh")
            //{
            //    user = new UserModel { Username = "******", EmailAddress = "*****@*****.**" };
            //}
            //return user;



            //using (SqlConnection con = new SqlConnection(connectionString))
            //{
            //string sqlQuery = "SELECT * FROM UserLogIn WHERE Username= '******'";
            //SqlCommand cmd = new SqlCommand(sqlQuery, con);

            //con.Open();

            //SqlDataReader rdr = cmd.ExecuteReader();
            //con.Close();
            // }

            #endregion

            SampleContext SampleEntities = new SampleContext();

            var User = SampleEntities.UserLogIn.FirstOrDefault(u => u.UserName == login.UserName &&
                                                               u.Password == login.Password);

            if (User != null)
            {
                //_logger.LogInfo("Fetching user info");

                //throw new Exception("Exception while fetching  user info.");

                return(User);
            }

            else
            {
                //_logger.LogInfo("Fetching user info");

                //throw new Exception("Exception while fetching  user info.");

                return(null);
            }
        }
示例#18
0
 public long AddInfo(UserLogIn model)
 {
     using (var db = new Db())
     {
         var entity = new UserLogIn
         {
             Name = model.Name
         };
         db.UserLogIns.Add(entity);
         db.SaveChanges();
         return(entity.Id);
     }
 }
示例#19
0
        public IActionResult Login([FromBody] UserLogIn login)
        {
            IActionResult response = Unauthorized();
            var           user     = AuthenticateUser(login);

            if (user != null)
            {
                var tokenString = GenerateJSONWebToken(user);
                response = Ok(new { token = tokenString + ", Username:"******", EmailAddress:" + user.Email });
            }
            _logger.LogInfo("Token generated");
            return(response);
        }
示例#20
0
        public async Task <ActionResult <UserToken> > Login([FromBody] UserLogIn model)
        {
            var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, isPersistent : false, lockoutOnFailure : false);

            if (result.Succeeded)
            {
                return(await BuildToken(model));
            }
            else
            {
                return(BadRequest("Invalid Login Attempt, Email or Password is incorrect!"));
            }
        }
示例#21
0
        // GET: UserLogIns/Edit/5
        public ActionResult Edit(string id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            UserLogIn userLogIn = db.UserLogIns.Find(id);

            if (userLogIn == null)
            {
                return(HttpNotFound());
            }
            return(View(userLogIn));
        }
        public string UserLogInDataValidation(UserLogIn userLogIn)
        {
            if (userLogIn.UserName == null)
            {
                return(loader.GetString("loginUserNameValidation"));
            }

            if (userLogIn.Password == null)
            {
                return(loader.GetString("loginPasswordValidation"));
            }

            return(null);
        }
示例#23
0
        protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int Id = Convert.ToInt32(gdUserInfo.DataKeys[e.RowIndex].Values[0]);

            using (OnlineStudentAdmissionEntities1 entities = new OnlineStudentAdmissionEntities1())
            {
                UserLogIn user = (from c in entities.UserLogIn
                                  where c.Id == Id
                                  select c).FirstOrDefault();
                entities.UserLogIn.Remove(user);
                entities.SaveChanges();
            }
            this.BindGrid();
        }
        public async Task <IActionResult> Create([Bind("userId,name,password,Email,phnNumber")] UserLogIn userLogIn)
        {
            if (ModelState.IsValid)
            {
                _context.Add(userLogIn);


                var studentsList = await _context.StudentsLists
                                   .FirstOrDefaultAsync(m => m.studentname == userLogIn.name);


                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(userLogIn));
        }
示例#25
0
        //[AllowAnonymous]
        //[HttpPost]
        //public IActionResult MyPage([FromBody]UserLogIn login)
        //{
        //    IActionResult response = Unauthorized();
        //    var user = AuthenticateUser(login);

        //    if (user != null)
        //    {
        //        var tokenString = GenerateJSONWebToken(user);
        //        response = Ok(new { token = tokenString + "Username:"******",EmailAddress:" + user.Email });
        //    }

        //    return response;
        //}


        private string GenerateJSONWebToken(UserLogIn userInfo)
        {
            ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[]
            {
                new Claim("UserName", userInfo.UserName)
            });
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(_config["Jwt:Issuer"],
                                             _config["Jwt:Issuer"],
                                             null,
                                             expires: DateTime.Now.AddMinutes(10),
                                             signingCredentials: credentials
                                             );

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
示例#26
0
 public async Task<IActionResult> LoginAsync([FromBody] UserLogIn userLogIn)
 {
     try
     {
         AccessToken accessToken = new AccessToken();
         var result = await _signManager.PasswordSignInAsync(userLogIn.Email, userLogIn.Password, false, false);
         if (result.Succeeded)
         {
             var user = await _userManager.FindByEmailAsync(userLogIn.Email);
          
             var tokenHandler = new JwtSecurityTokenHandler();
             var key = Encoding.ASCII.GetBytes(_appSettings.SecurityKey);
             string protectorUserId = _protector.Protect(user.Id.ToString()) ;
         
             var tokenDescriptor = new SecurityTokenDescriptor
             {
                 Subject = new ClaimsIdentity(new Claim[]
                 {
                     new Claim(ClaimTypes.NameIdentifier, protectorUserId),
                     new Claim(ClaimTypes.Email, user.Email),
                     new Claim(ClaimTypes.Name, user.FirstName),
                       new Claim ("UserId", protectorUserId)
                 }),
                 Expires = DateTime.UtcNow.AddDays(7),
                 SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
             };
             accessToken.StatusCode = 200;
             accessToken.ExpireTime = DateTime.UtcNow.AddDays(7);
             var token = tokenHandler.CreateToken(tokenDescriptor);
             accessToken.Token = tokenHandler.WriteToken(token);
             return Ok(accessToken);
         }
         else
         {
           return BadRequest("Username or Password is Invalid");
         }
       
     }
     catch (Exception ex)
     {
         return BadRequest(ex.Message);
     }
 }
示例#27
0
        protected void Insert(object sender, EventArgs e)
        {
            using (OnlineStudentAdmissionEntities1 entities = new OnlineStudentAdmissionEntities1())
            {
                UserLogIn user = new UserLogIn
                {
                    Username  = txtUserName.Text,
                    Password  = txtPassword.Text,
                    IsAdmin   = false,
                    LoginDate = System.DateTime.Now
                };
                entities.UserLogIn.Add(user);
                entities.SaveChanges();
                txtPassword.Text = "";
                txtUserName.Text = "";
            }

            this.BindGrid();
        }
示例#28
0
        protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            GridViewRow row      = gdUserInfo.Rows[e.RowIndex];
            int         Id       = Convert.ToInt32(gdUserInfo.DataKeys[e.RowIndex].Values[0]);
            string      name     = (row.FindControl("txtName") as TextBox).Text;
            string      password = (row.FindControl("txtPassword") as TextBox).Text;

            using (OnlineStudentAdmissionEntities1 entities = new OnlineStudentAdmissionEntities1())
            {
                UserLogIn user = (from c in entities.UserLogIn
                                  where c.Id == Id
                                  select c).FirstOrDefault();
                user.Username = name;
                user.Password = password;
                entities.SaveChanges();
            }
            gdUserInfo.EditIndex = -1;
            this.BindGrid();
        }
示例#29
0
        public string GetUser(UserLogIn userLogIn)
        {
            User user = (from a in db.User
                         where a.Email == userLogIn.Email
                         select a).FirstOrDefault();

            if (user == null)
            {
                return("EmailIsNotValid");
            }
            if (user.PasswordHash == userLogIn.PasswordHash)
            {
                return("true");
            }
            else
            {
                return("PasswordIsInCorrect");
            }
        }
示例#30
0
        public async Task <ActionResult <UserToken> > CreateUser([FromBody] UserRegister model)
        {
            var user = new IdentityUser {
                UserName = model.Email, Email = model.Email, PhoneNumber = model.PhoneNumber
            };
            var result = await _userManager.CreateAsync(user, model.Password);

            if (result.Succeeded)
            {
                var UserLogIn = new UserLogIn {
                    Email = model.Email, Password = model.Password
                };
                return(await BuildToken(UserLogIn));
            }
            else
            {
                return(BadRequest("This User has already Registered!"));
            }
        }