Beispiel #1
0
        public async Task GetLoggedInUserInfo(string token)
        {
            apiClient.DefaultRequestHeaders.Clear();
            apiClient.DefaultRequestHeaders.Accept.Clear();
            apiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            apiClient.DefaultRequestHeaders.Add("Authorization", $"bearer {token}");
            using (HttpResponseMessage httpResponseMessage = await apiClient.GetAsync("/api/User"))
            {
                if (httpResponseMessage.IsSuccessStatusCode)
                {
                    LoggedInUserModel result = await httpResponseMessage.Content.ReadAsAsync <LoggedInUserModel>();

                    _loggedInUserModel.CreatedDate  = result.CreatedDate;
                    _loggedInUserModel.EmailAddress = result.EmailAddress;
                    _loggedInUserModel.Id           = result.Id;
                    _loggedInUserModel.FirstName    = result.FirstName;
                    _loggedInUserModel.LastName     = result.LastName;
                    _loggedInUserModel.Token        = result.Token;
                }
                else
                {
                    throw new Exception(httpResponseMessage.ReasonPhrase);
                }
            }
        }
        public LoggedInUserModel Authenticate(string username, string password)
        {
            User user = _userManager.FindByNameAsync(username).Result;

            if (user == null || !_userManager.CheckPasswordAsync(user, password).Result)
            {
                return(null);
            }

            var    tokenHandler    = new JwtSecurityTokenHandler();
            var    key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
            string userRole        = _userManager.GetRolesAsync(user).Result.FirstOrDefault();
            var    tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.Id),
                    new Claim(ClaimTypes.Role, userRole)
                }),
                Expires            = DateTime.UtcNow.AddHours(_appSettings.TokenExpiresTimeHours),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);

            LoggedInUserModel userWithToken = new LoggedInUserModel()
            {
                UserId = user.Id,
                Role   = userRole,
                Token  = tokenHandler.WriteToken(token)
            };

            return(userWithToken);
        }
Beispiel #3
0
        public async Task GetLoggedInUserInfo(string token)
        {
            _apiClient.DefaultRequestHeaders.Clear();
            _apiClient.DefaultRequestHeaders.Accept.Clear();
            _apiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            _apiClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}"); //for every call it will use token. once username and password is entered.

            // data to endpoints
            using (HttpResponseMessage response = await _apiClient.GetAsync("/api/User"))
            {
                if (response.IsSuccessStatusCode)
                {
                    var json = await response.Content.ReadAsStringAsync();

                    LoggedInUserModel result = JsonConvert.DeserializeObject <LoggedInUserModel>(json);
                    _loggedInUser.CreatedDate  = result.CreatedDate;
                    _loggedInUser.EmailAddress = result.EmailAddress;
                    _loggedInUser.FirstName    = result.FirstName;
                    _loggedInUser.Id           = result.Id;
                    _loggedInUser.LastName     = result.LastName;
                    _loggedInUser.Token        = token;
                }
                else
                {
                    throw new Exception(response.ReasonPhrase);
                }
            }
        }
Beispiel #4
0
        public async Task <LoggedInUserModel> LoginUser(LoginModel model)
        {
            var validUser = _repo.User.FindAll().FirstOrDefault(x => x.Email.ToLower().Equals(model.Email.ToLower()));

            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[] {
                    new Claim(ClaimTypes.Name, validUser.Id),
                    new Claim(ClaimTypes.Email, validUser.Email)
                    // TODO: Add roles
                }),
                Expires            = DateTime.UtcNow.AddHours(8),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);
            var user  = new LoggedInUserModel
            {
                UserId   = Guid.Parse(validUser.Id),
                UserName = validUser.UserName,
                Email    = validUser.Email,
                School   = validUser.School,
                Region   = validUser.Region,
                Token    = tokenHandler.WriteToken(token)
            };

            return(user);
        }
        /// <summary>
        /// method is used for validate application users
        /// </summary>
        /// <param name="Logininfo"></param>
        /// <returns></returns>
        public object GetLoginUser(LoginUserModel Logininfo)
        {
            APIResponse       _response        = new APIResponse();
            LoggedInUserModel lgAppUserDetails = new LoggedInUserModel();
            object            objLgAppUserDetails;

            try
            {
                using (dbcontext = new AlertBackEntities())
                {
                    Logininfo.UserName = Logininfo.UserName.ToLower();
                    tblApplicationUser lgDetail = dbcontext.tblApplicationUsers.FirstOrDefault(x => x.UserName.ToLower() == Logininfo.UserName && x.IsDeleted == false);

                    if (lgDetail != null)
                    {
                        if (lgDetail.Password == Logininfo.Password)
                        {
                            lgAppUserDetails.ApplicationUserId = lgDetail.ApplicationUserId;
                            lgAppUserDetails.UserIdentityKey   = lgDetail.UserIdentityKey;
                            lgAppUserDetails.success           = true;
                            lgAppUserDetails.ErrorMessage      = "User Authenticated!!";
                            lgAppUserDetails.Name        = lgDetail.Name == null ? "" : lgDetail.Name;
                            lgAppUserDetails.EmailId     = lgDetail.EmailId;
                            lgAppUserDetails.MobileNo    = lgDetail.MobileNo;
                            lgAppUserDetails.Gender      = lgDetail.Gender;
                            lgAppUserDetails.DateOfBirth = lgDetail.DateOfBirth;
                            lgAppUserDetails.Address     = lgDetail.Address;
                            lgAppUserDetails.FatherName  = lgDetail.tblMember == null ? "" : lgDetail.tblMember.FatherName;
                            lgAppUserDetails.MotherName  = lgDetail.tblMember == null ? "" : lgDetail.tblMember.MotherName;
                            lgAppUserDetails.UserName    = lgDetail.UserName;

                            _response.Message  = "User Authenticated!!";
                            _response.IsSucess = true;
                        }
                        else
                        {
                            lgAppUserDetails.ErrorMessage = "Invalid password!!";
                            _response.Message             = "Invalid password!!";
                            _response.IsSucess            = false;
                        }
                    }
                    else
                    {
                        lgAppUserDetails.ErrorMessage = "Invalid username!!";
                        _response.Message             = "Invalid username!!";
                        _response.IsSucess            = false;
                    }
                }
            }
            catch (Exception ex)
            {
                lgAppUserDetails              = null;
                objLgAppUserDetails           = null;
                dbcontext                     = null;
                lgAppUserDetails.ErrorMessage = ex.Message.ToString();
            }
            objLgAppUserDetails = lgAppUserDetails;
            return(objLgAppUserDetails);
        }
        public IActionResult Index(string First_Name, string Last_Name, string Email, string Home_Planet, string Current_Captain, string orderID)
        {
            LoggedInUserModel user = CreateUser(First_Name, Last_Name, Email, Home_Planet, Current_Captain);
            ShopModel         shop;

            if (orderID is null || orderID == "")
            {
                shop = new ShopModel(user);
            }
Beispiel #7
0
        /*
         * Handlers for external events
         */
        #region external_events

        private void OnConnectAccept(LoggedInUserModel model)
        {
            if (this.InvokeRequired)
            {
                this.Invoke((LogoutController.ExternalEventHandler)
                            OnConnectAccept, model);
                return;
            }
            this.Visible = true;
        }
        public LoggedInUserModel AuthenticateUser(string username, string password)
        {
            var queryUser = _context.Users.Join(
                _context.UserRoles,
                u => u.UserId,
                ur => ur.UserId,
                (u, ur) => new { u, ur }
                )
                            .Where(u => u.u.Email == username && u.u.Password == password).Take(1)
                            .Join(
                _context.Roles,
                ur => ur.ur.RoleId,
                r => r.RoleId,
                (ur, r) => new LoggedInUserModel
            {
                UserId     = ur.u.UserId,
                Username   = ur.u.Username,
                Cellphone  = ur.u.Cellphone,
                Email      = ur.u.Email,
                CreateDate = ur.u.CreateDate,
                Role       = r.Name
            }
                );

            var loggedInUser = new LoggedInUserModel();

            foreach (var u in queryUser)
            {
                loggedInUser = u;
            }

            if (loggedInUser == null)
            {
                return(null);
            }

            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, loggedInUser.Email),
                    new Claim(ClaimTypes.Role, loggedInUser.Role),
                    new Claim(ClaimTypes.MobilePhone, loggedInUser.Cellphone),
                }),
                Expires            = DateTime.UtcNow.AddHours(2),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);

            loggedInUser.Token = tokenHandler.WriteToken(token);

            return(loggedInUser);
        }
        private LoggedInUserModel CreateUser(string First_Name, string Last_Name, string Email, string Home_Planet, string Current_Captain)
        {
            LoggedInUserModel m = new LoggedInUserModel();

            m.values[LoggedInUserModel.FIRST_NAME]      = First_Name;
            m.values[LoggedInUserModel.LAST_NAME]       = Last_Name;
            m.values[LoggedInUserModel.EMAIL]           = Email;
            m.values[LoggedInUserModel.HOME_PLANET]     = Home_Planet;
            m.values[LoggedInUserModel.CURRENT_CAPTAIN] = Current_Captain;

            return(m);
        }
        public IActionResult Authenticate([FromBody] LoginViewModel model)
        {
            var user = new LoggedInUserModel();

            user = _userService.AuthenticateUser(model.Email, model.Password);

            if (user == null)
            {
                return(NotFound());
            }
            return(Ok(user));
        }
        public IActionResult Login([FromForm] AuthenticateModel model)
        {
            LoggedInUserModel userWithJWT = _userService.Authenticate(model.Username, model.Password);

            if (userWithJWT == null)
            {
                return(BadRequest(new { message = "Username or password is incorrect" }));
            }

            _logger.LogInformation("Login succes. User: {User}", model.Username);

            return(Ok(userWithJWT));
        }
Beispiel #12
0
 public List <UserListModel> Get(LoggedInUserModel userInfo)
 {
     return(_userRepository.All()
            .Select(n => new UserListModel
     {
         Id = n.Id,
         FirstName = n.FirstName,
         MiddleName = n.MiddleName,
         LastName = n.LastName,
         Email = n.Email,
         Mobile = n.Mobile,
         DateOfBirth = string.Format("{0:dd/MM/yyyy}", n.DateOfBirth)
     }).ToList());
 }
Beispiel #13
0
 private void OnGetUserInfoFromServer(LoggedInUserModel model)
 {
     while (!this.IsHandleCreated)
     {
         ;
     }
     if (this.InvokeRequired)
     {
         this.Invoke((LogoutController.ExternalEventHandler)
                     OnGetUserInfoFromServer, model);
         return;
     }
     MyAccountButton.Enabled = true;
     new MyAccountView();
 }
        public LoggedInUserModel LoginEncryptedUser(string userName, string password)
        {
            string            token = Guid.NewGuid().ToString();
            LoggedInUserModel model = this._IUserRepository.ValidateEncryptedUserLogin(userName, password, 0, 0);
            var         dic         = new Dictionary <string, SessionData>();
            SessionData sessionData = new SessionData();

            sessionData.UserId         = model.UserId;
            sessionData.OrganizationId = model.OrganizationId;
            sessionData.RoleId         = model.RoleList;
            sessionData.ExpirationDate = DateTime.Now.AddHours(2);
            dic.Add(token, sessionData);
            this._caching.SessionModel = dic;
            model.Token = token;
            return(model);
        }
Beispiel #15
0
        private void OnDisconnect(LoggedInUserModel model)
        {
            if (this.InvokeRequired)
            {
                this.Invoke((LoginController.ExternalEventHandler)
                            OnDisconnect, model);
                return;
            }

            this.Visible = false;
            ReachWindow e = (ReachWindow)Context.EntryPoint;

            e.CloseAllChildren();
            e.HideItemsInToolbar();
            e.ShowLoginWindow();
        }
Beispiel #16
0
        private void OnConnectDeny(LoggedInUserModel model)
        {
            while (!this.IsHandleCreated)
            {
                ;
            }
            if (this.InvokeRequired)
            {
                this.Invoke((LoginController.ExternalEventHandler)
                            OnConnectDeny, model);
                return;
            }

            this.Enabled         = true;
            errorMessage.Visible = true;
            errorMessage.Text    = INVALID_CREDENTIALS_ERROR;
        }
Beispiel #17
0
        private void OnConnectTimeOut(LoggedInUserModel model)
        {
            while (!this.IsHandleCreated)
            {
                ;
            }
            if (this.InvokeRequired)
            {
                this.Invoke((LoginController.ExternalEventHandler)
                            OnConnectTimeOut, model);
                return;
            }

            this.Enabled         = true;
            errorMessage.Visible = true;
            errorMessage.Text    = TIMEOUT_ERROR;
        }
Beispiel #18
0
        public LoggedInUserModel GetLoggedInUserDetails()
        {
            LoggedInUserModel loggedInUser = new LoggedInUserModel();
            var userNameClaimValue         = this.httpContext.HttpContext.User.Claims.Where(x => x.Type == ClaimTypes.Name).Select(x => x.Value).FirstOrDefault();

            if (!string.IsNullOrWhiteSpace(userNameClaimValue))
            {
                loggedInUser = this.context.User.Where(x => x.Username == userNameClaimValue).Select(x => new LoggedInUserModel()
                {
                    UserId       = x.Id,
                    Username     = x.Username,
                    EmailAddress = x.EmailAddress
                }).FirstOrDefault();
            }

            return(loggedInUser);
        }
Beispiel #19
0
        public static List <UserListModel> Get(LoggedInUserModel userInfo)
        {
            var user = new List <UserListModel>();

            using (SchoolDataContext dbcontext = new SchoolDataContext())
            {
                user = dbcontext.User.Select(n => new UserListModel
                {
                    Id          = n.Id,
                    FirstName   = n.FirstName,
                    MiddleName  = n.MiddleName,
                    LastName    = n.LastName,
                    Email       = n.Email,
                    Mobile      = n.Mobile,
                    DateOfBirth = string.Format("{0:dd/MM/yyyy}", n.DateOfBirth)
                }).ToList();
            }
            return(user);
        }
Beispiel #20
0
 public void Login(string username, string password)
 {
     try
     {
         if (Helper.CheckUsername(username))
         {
             UserModel         user       = AuthDataAccess.AttemptLogin(username, password);
             LoggedInUserModel LoggedUser = new LoggedInUserModel()
             {
                 Id    = user.Id,
                 Token = Helper.GetUserToken(user.Id)
             };
         }
     }
     catch (Exception e)
     {
         throw new Exception(e.Message);
     }
 }
Beispiel #21
0
        /*
         * Handlers for external events
         */
        #region external_events

        private void OnConnectAccept(LoggedInUserModel model)
        {
            while (!this.IsHandleCreated)
            {
                ;
            }
            if (this.InvokeRequired)
            {
                this.Invoke((LoginController.ExternalEventHandler)
                            OnConnectAccept, model);
                return;
            }

            errorMessage.Visible = false;

            // Start the new views
            new QuestionListView();
            new FriendListView();
            ((ReachWindow)(Context.EntryPoint)).ShowItemsInToolbar();

            this.Close();
        }
Beispiel #22
0
        public LoggedInUserModel ValidateUserLogin(string userName, string password, int LoggedInUserId, int LoggedInOrganizationId)
        {
            LoggedInUserModel model             = new LoggedInUserModel();
            string            decryptedPassword = AES.Encrypt(password);

            try
            {
                var user = this.Get(x => x.UserName.Equals(userName) && x.Password.Equals(decryptedPassword) && x.InActive == true);
                if (user != null && user.UserID > 0)
                {
                    model.IsNewUser      = Convert.ToBoolean(user.IsNewUser);
                    model.UserId         = user.UserID;
                    model.UserName       = user.UserName;
                    model.Password       = user.Password;
                    model.OrganizationId = user.OrganizationID;
                    model.RoleList       = this._IUserRoleRepository.GetAll(user.UserID, user.OrganizationID, user.UserID).Select(x => x.RoleId).ToList <int>();
                }
            }
            catch (Exception ex)
            {
            }
            return(model);
        }
Beispiel #23
0
        public bool AuthenticateUser(LoginViewModel model)
        {
            var user = _userRepo
                       .FindBy(m => m.Email.Equals(model.UserNameOrEmail, StringComparison.OrdinalIgnoreCase) ||
                               m.UserName.Equals(model.UserNameOrEmail, StringComparison.OrdinalIgnoreCase))
                       .FirstOrDefault();

            if (user == null)
            {
                return(false);
            }

            if (user.Password != model.Password)
            {
                return(false);
            }

            var loggedInUserModel = new LoggedInUserModel(user);

            ProjectSession.LoggedInUser          = loggedInUserModel;
            ProjectSession.UserAccessPermissions = GetUserPermissions(user.RoleId, user.IsSuperAdmin);

            return(true);
        }
Beispiel #24
0
        public string GetCurrentLoggedInUserName()
        {
            LoggedInUserModel loggedInUser = new LoggedInUserModel();

            return(this.httpContext.HttpContext.User.Claims.Where(x => x.Type == ClaimTypes.Name).Select(x => x.Value).FirstOrDefault());
        }
Beispiel #25
0
        public void ShowUserInfo()
        {
            LoggedInUserModel model = LoggedInUserModel.Instance;

            loggedInUser.Text = model.User.Username;
            crtRating.Text    = model.User.Rank.ToString("0.000");

            // Display all the domains for which the user is certificated
            int maxHeight = 0;

            certs.Items.Clear();
            for (int i = 0; i < model.CertifiedDomains.Count; ++i)
            {
                certs.Items.Add(model.CertifiedDomains[i].Name);
            }
            certs.Size          = new Size(235, 4 + model.CertifiedDomains.Count * 16);
            certsContainer.Size = new Size(248, certs.Height + 15);

            label2.Location           = new Point(25, certsContainer.Location.Y + certsContainer.Height + 2);
            pictureBox4.Location      = new Point(-2, label2.Location.Y - 8);
            uncertsContainer.Location = new Point(6, label2.Location.Y + 20);

            // Display all the domains for which a user can receive a certificate
            int index = 0;

            foreach (DomainData item in model.AllDomains)
            {
                bool found = false;
                for (int i = 0; i < model.CertifiedDomains.Count && !found; ++i)
                {
                    found = (model.CertifiedDomains[i].ID == item.ID);
                }
                if (found)
                {
                    continue;
                }

                // the label with the domain
                Label domainTitle = new Label();
                domainTitle.Location = new Point(7, 12 + 27 * index);
                domainTitle.Font     = UI_FONT;
                domainTitle.Text     = item.Name + ":";
                domainTitle.Visible  = true;
                uncertsContainer.Controls.Add(domainTitle);

                // the button for obtaining the certificate
                CertButton btn = new CertButton();
                btn.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(209)))), ((int)(((byte)(228)))));
                btn.FlatAppearance.BorderColor        = System.Drawing.Color.FromArgb(((int)(((byte)(111)))), ((int)(((byte)(150)))), ((int)(((byte)(193)))));
                btn.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(44)))), ((int)(((byte)(87)))), ((int)(((byte)(147)))));
                btn.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(85)))), ((int)(((byte)(130)))), ((int)(((byte)(182)))));
                btn.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
                btn.Font      = UI_FONT;
                btn.ForeColor = System.Drawing.Color.Black;
                btn.Size      = new System.Drawing.Size(115, 25);
                btn.Location  = new System.Drawing.Point(127, 8 + index * (btn.Height + 2));
                btn.Margin    = new System.Windows.Forms.Padding(3, 2, 3, 2);
                btn.TabIndex  = 100 + index;
                btn.Text      = "Get a Certificate";
                btn.UseVisualStyleBackColor = false;
                btn.Click += new EventHandler(btn_Click);
                btn.domain = item;
                uncertsContainer.Controls.Add(btn);

                ++index;
                maxHeight = btn.Location.Y + btn.Height;
            }

            uncertsContainer.Height = maxHeight + 10;
            this.Size = new Size(
                this.Width,
                uncertsContainer.Location.Y + uncertsContainer.Height + 30);
        }