Пример #1
0
        public async Task <IHttpActionResult> GetUserInfo(string userName = null)
        {
            using (var context = new ApplicationDbContext())
            {
                var        userStore   = new UserStore <ApplicationUserModel>(context);
                var        userManager = new UserManager <ApplicationUserModel>(userStore);
                var        roles       = context.Roles.ToList();
                UserReturn userReturn  = null;
                string     id          = null;
                Test1      user_       = null;
                if (userName == null)
                {
                    id    = RequestContext.Principal.Identity.GetUserId();
                    user_ = await db.Test1.FindAsync(id);
                }
                else
                {
                    user_ = db.Test1.Where(q => q.Nickname == userName).FirstOrDefault();

                    if (user_ == null)
                    {
                        return(StatusCode(HttpStatusCode.NotFound));
                    }
                    id = user_.Id;
                    var userCurrent = await userManager.FindByIdAsync(RequestContext.Principal.Identity.GetUserId());

                    string roleId       = roles.Where(q => q.Name == "Admin").FirstOrDefault().Id;
                    var    userIsInRole = userCurrent.Roles.Where(q => q.RoleId == roleId && q.UserId == userCurrent.Id).FirstOrDefault();



                    if (userIsInRole == null)
                    {
                        return(StatusCode(HttpStatusCode.Unauthorized));
                    }
                    //if (user_ == null)
                    //{
                    //    return null;
                    //}
                }

                var user = await userManager.FindByIdAsync(id);



                if (user_ == null)
                {
                    return(StatusCode(HttpStatusCode.NotFound));
                }
                else
                {
                    userReturn = new UserReturn(user_);
                    foreach (var r in user.Roles)
                    {
                        userReturn.Roles.Add(roles.Where(q => q.Id == r.RoleId).FirstOrDefault().Name);
                    }
                }
                return(Ok(userReturn));;
            }
        }
        public UserReturn Authenticate(string username, string password)
        {
            User user = _userService.Find(username, password);

            // return null if user not found
            if (user == null)
            {
                return(null);
            }

            // authentication successful so generate jwt token
            JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();

            byte[] key = Encoding.ASCII.GetBytes(_userSettings.Secret);
            SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.Id.ToString())
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            SecurityToken token      = tokenHandler.CreateToken(tokenDescriptor);
            UserReturn    userReturn = (UserReturn)user;

            userReturn.Token = tokenHandler.WriteToken(token);

            return(userReturn);
        }
Пример #3
0
        public async Task <List <UserReturn> > GetAllUserInfo()
        {
            List <Test1>      users  = db.Test1.ToList();
            List <UserReturn> output = new List <UserReturn>();

            using (var context = new ApplicationDbContext())
            {
                var userStore   = new UserStore <ApplicationUserModel>(context);
                var userManager = new UserManager <ApplicationUserModel>(userStore);
                var roles       = context.Roles.ToList();
                foreach (var userLocal in users)
                {
                    UserReturn userReturn;
                    var        user = await userManager.FindByIdAsync(userLocal.Id);

                    userReturn = new UserReturn(userLocal);
                    if (user != null)
                    {
                        foreach (var r in user.Roles)
                        {
                            userReturn.Roles.Add(roles.Where(q => q.Id == r.RoleId).FirstOrDefault().Name);
                        }
                    }

                    output.Add(userReturn);
                }



                return(output);
            }
        }
        public static string GenerateTokenUser(
            UserReturn user,
            IConfiguration configuration)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var key          = Encoding.ASCII.GetBytes(configuration.GetSection("AppSettings:Token").Value);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.NameIdentifier
                              , user.Id.ToString()),
                    new Claim(ClaimTypes.Name, user.Name.ToString()),
                    new Claim(ClaimTypes.Email, user.Email.ToString()),
                    new Claim(ClaimTypes.Role, user.Role.ToString())
                }),
                Expires            = DateTime.UtcNow.AddHours(2),
                SigningCredentials =
                    new SigningCredentials(
                        new SymmetricSecurityKey(key),
                        SecurityAlgorithms.HmacSha256Signature)
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(tokenHandler.WriteToken(token));
        }
Пример #5
0
        public UserReturn getUserById(UserReturn statusParam)
        {
            if (statusParam == null)
            {
                throw new AppExceptions("User Id is required");
            }
            var        _user          = GetUserById(statusParam.Id);
            UserReturn _getUserReturn = new UserReturn();

            if (_user != null)
            {
                _getUserReturn.Id          = _user.Id;
                _getUserReturn.Username    = _user.Username;
                _getUserReturn.FirstName   = _user.FirstName;
                _getUserReturn.LastName    = _user.LastName;
                _getUserReturn.Email       = _user.Email;
                _getUserReturn.Description = _user.Description;
                _getUserReturn.Group       = _user.Group;
                _getUserReturn.accessCode  = _user.accessCode;
            }
            else
            {
                throw new AppExceptions("User not found");
            }
            return(_getUserReturn);
        }
Пример #6
0
        public static void UpdateCanvasData(int?idEntidad, UserReturn newUser)
        {
            logger.Info("UserDAL/UpdateCanvasData - Task 'Update user data from Canvas' STARTED");
            if (newUser != null)
            {
                using (var context = new CANVAS_Model_Entities())
                {
                    uniCanvasUsuario newCanvasUser = context.uniCanvasUsuarios.Where(x => x.IDAcademico == idEntidad).FirstOrDefault();
                    if (newUser.error_message == null)
                    {
                        newCanvasUser.Estado   = CanvasWebApi.Common.ConfigEnum.CanvasState.Sincronizado.GetHashCode();
                        newCanvasUser.Fecha    = DateTime.Now;
                        newCanvasUser.IDCanvas = Int32.Parse(newUser.id);
                    }
                    else
                    {
                        newCanvasUser.Estado = CanvasWebApi.Common.ConfigEnum.CanvasState.Error.GetHashCode();
                    }

                    newCanvasUser.Error = newUser.error_message;
                    context.SaveChanges();
                }
                logger.Info("UserDAL/UpdateCanvasData - Task 'Update user data from Canvas' FINISHED");
            }
            logger.Info("UserDAL/UpdateCanvasData - Task 'Update user data from Canvas' FINISHED");
        }
Пример #7
0
        public IActionResult Login(UserLogin user)
        {
            UserReturn userGet = _authenticationService.Authenticate(user.Username, user.Password);

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

            return(Ok(userGet));
        }
Пример #8
0
 public IActionResult GetUser([FromBody] UserReturn statusParam)
 {
     try
     {
         var _userReturn = _loginService.getUserById(statusParam);
         return(Ok(_userReturn));
     }
     catch (Exception ex)
     {
         return(BadRequest(new { message = ex.Message }));
     }
 }
Пример #9
0
        public async Task <ActionResult <UserReturn> > Register(RegisterInfo registerInfo)
        {
            try
            {
                UserReturn userReturn = await _authService.Register(registerInfo);

                return(Ok(userReturn));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Пример #10
0
        public async Task <ActionResult <UserReturn> > Login(LoginInfo loginInfo)
        {
            try
            {
                UserReturn userReturn = await _authService.Login(loginInfo);

                return(Ok(userReturn));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Пример #11
0
        /// <summary>
        /// 类型:方法
        /// 名称:UserOnline
        /// 作者:taixihuase
        /// 作用:通过接收并添加一个用户信息进行登录
        /// 编写日期:2015/7/12
        /// </summary>
        /// <param name="user"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public UserReturn UserOnline(UserInfo user, string password)
        {
            // 从数据库获取用户信息
            UserReturn userReturn = Server.Data.UserData.GetUserInfo(user, password);

            #region 判断用户登录信息是否正确,正确则尝试登录,错误则直接返回

            if (userReturn.ReturnCode == UserReturn.ReturnCodeType.Default)
            {
                lock (this)
                {
                    // 如果已查得登录信息
                    if (GuidToUniqueId.ContainsKey(user.Guid) || AccountToUniqueId.ContainsKey(user.Account) ||
                        UniqueIdToUser.ContainsKey(user.UniqueId))
                    {
                        userReturn.ReturnCode = RepeatedLogin;
                        userReturn.DebugMessage.Append("重复登录!");
                    }
                    else
                    {
                        // 添加用户信息

                        GuidToUniqueId.Add(user.Guid, user.UniqueId);

                        user.LoginTime = DateTime.Now;
                        user.Status    = Loginning;

                        UniqueIdToUser.Add(user.UniqueId, user);
                        if (!AccountToUniqueId.ContainsKey(user.Account))
                        {
                            AccountToUniqueId.Add(user.Account, user.UniqueId);
                        }
                        if (!NicknameToUniqueId.ContainsKey(user.Nickname))
                        {
                            NicknameToUniqueId.Add(user.Nickname, user.UniqueId);
                        }

                        userReturn.ReturnCode = Success;
                        userReturn.DebugMessage.Append("登录成功!");
                    }
                }
            }

            #endregion

            return(userReturn);
        }
Пример #12
0
        public static void SyncToCanvas()
        {
            logger.Info("UserService/SyncToCanvas - Task 'Sync user' STARTED");

            try
            {
                SyncronizationDAL.SyncToCanvas();

                List <sp_get_uniCanvas_ws_usuarios_Result> userSyncList = UserDAL.SyncToCanvas();
                List <string> createdUserList = new List <string>();

                foreach (sp_get_uniCanvas_ws_usuarios_Result userSync in userSyncList)
                {
                    try
                    {
                        UserController userController = new UserController();
                        User           user           = new Common.User();
                        user.user = new Common.UserDTO(userSync);

                        if (!createdUserList.Any(x => x == userSync.Username))
                        {
                            UserReturn newUser = (UserReturn)userController.Create(user);

                            if (newUser != null)
                            {
                                UserDAL.UpdateCanvasData(userSync.IDAcademico, newUser);
                                createdUserList.Add(userSync.Username);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        UserReturn newUser = new UserReturn()
                        {
                            error_message = e.Message
                        };
                        UserDAL.UpdateCanvasData(userSync.IDAcademico, newUser);
                    }
                }
                logger.Info("UserService/SyncToCanvas - Task 'Sync user' FINISHED");
            }
            catch (Exception e)
            {
                logger.Error("UserService/SyncToCanvas - Task 'Sync user' FINISHED WITH ERROR: \n " + "  Message: " + e.Message + "\nInner Exception: " + e.InnerException);
            }
        }
Пример #13
0
        public async Task <UserReturn> CreateAsync(Cosmos_db_api.Models.User user)
        {
            var userRet = new UserReturn();

            try
            {
                user.id = Guid.NewGuid();
                var userResp = await this._container.CreateItemAsync <Models.User>(user, new PartitionKey(user.id.ToString()));

                userRet.Id = ((Models.User)userResp.Resource).id;
            }
            catch (CosmosException ex)
            {
                userRet.ErrorMessages.Add($"Error creating user: {ex.Message}");
            }
            return(userRet);
        }
Пример #14
0
        public async Task <UserReturn> CreateAsync(User user)
        {
            var userRet = new UserReturn();

            if (String.IsNullOrEmpty(user?.FirstName))
            {
                userRet.ErrorMessages.Add("The User First Name is required");
            }
            if (String.IsNullOrEmpty(user?.LastName))
            {
                userRet.ErrorMessages.Add("The User Last Name is required");
            }
            if (String.IsNullOrEmpty(user?.EmailAddress))
            {
                userRet.ErrorMessages.Add("The User email address is required");
            }
            userRet = await _userService.CreateAsync(user);

            return(userRet);
        }
Пример #15
0
        public List <UserReturn> Users()
        {
            var _users = ListUsers();
            List <UserReturn> __userListReturn = new List <UserReturn>();

            if (_users != null)
            {
                foreach (User user in _users)
                {
                    UserReturn ur = new UserReturn();
                    ur.Id         = user.Id;
                    ur.Username   = user.Username;
                    ur.FirstName  = user.FirstName;
                    ur.LastName   = user.LastName;
                    ur.Email      = user.Email;
                    ur.Group      = user.Group.ToString();
                    ur.accessCode = user.accessCode;

                    __userListReturn.Add(ur);
                }
            }
            return(__userListReturn);
        }