コード例 #1
0
        public IActionResult Login(StudentLoginRequest request)
        {
            var student = service.GetLoggingStudent(request);

            if (student == null)
            {
                return(Unauthorized("Student o podanym indeksie i haśle nie istnieje w bazie danych!"));
            }
            var claims = new Claim[]
            {
                new Claim(ClaimTypes.NameIdentifier, student.IndexNumber),
                new Claim(ClaimTypes.Name, student.FirstName),
                new Claim(ClaimTypes.Role, "student")
            };

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

            var token = new JwtSecurityToken
                        (
                issuer: "Gakko",
                audience: "Students",
                claims: claims,
                expires: DateTime.Now.AddMinutes(10),
                signingCredentials: creds
                        );

            return(Ok(new
            {
                token = new JwtSecurityTokenHandler().WriteToken(token),
                refreshToken = Guid.NewGuid()
            }));
        }
コード例 #2
0
 public Student GetLoggingStudent(StudentLoginRequest request)
 {
     using (var con = new SqlConnection(ConString))
         using (var com = new SqlCommand())
         {
             com.Connection = con;
             con.Open();
             com.CommandText = "SELECT * FROM Student WHERE IndexNumber=@index AND Password=@password";
             com.Parameters.AddWithValue("index", request.IndexNumber);
             com.Parameters.AddWithValue("password", request.Password);
             var dr = com.ExecuteReader();
             if (!dr.HasRows)
             {
                 return(null);
             }
             else
             {
                 Student student = new Student();
                 while (dr.Read())
                 {
                     student.FirstName    = dr["FirstName"].ToString();
                     student.LastName     = dr["LastName"].ToString();
                     student.IndexNumber  = dr["IndexNumber"].ToString();
                     student.BirthDate    = DateTime.Parse(dr["BirthDate"].ToString());
                     student.IdEnrollment = (int)dr["IdEnrollment"];
                 }
                 dr.Close();
                 return(student);
             }
         }
 }
コード例 #3
0
        /// <summary>
        /// 把解密的数据转成字符串,方便出现异常可能通过此数据进行调试
        /// <para>作    者:蔡亚康</para>
        /// <para>创建时间:2019-03-18</para>
        /// </summary>
        /// <param name="request">登陆请求数据</param>
        /// <param name="openid">用户的OPENID信息</param>
        /// <returns></returns>
        private string GetDecryptData(StudentLoginRequest request, OpenIdResponse openid)
        {
            StringBuilder sbMsg = new StringBuilder();

            sbMsg.Append(JsonConvert.SerializeObject(request));
            sbMsg.Append(JsonConvert.SerializeObject(openid));
            return(sbMsg.ToString());
        }
コード例 #4
0
        public StringResult LoginStudent([FromBody] StudentLoginRequest student)
        {
            if (string.IsNullOrEmpty(student.Username) || string.IsNullOrEmpty(student.Password))
            {
                return(StringResult.Error("Username and password cannot be blank"));
            }

            var loginResult = studentBl.LoginStudent(student.Username, student.Password);

            if (loginResult.Success)
            {
                var secretKey = configuration[CONSTANTS.Keys.JWT_SECRETKEY];
                var issuer    = configuration[CONSTANTS.Keys.JWT_ISSUER];
                var audience  = configuration[CONSTANTS.Keys.JWT_AUDIENCE];
                var token     = JwtHandler.GenerateAPIToken(loginResult.ResultOk.ToString(), secretKey, issuer, audience);
                return(StringResult.Ok(token));
            }
            else
            {
                var result = StringResult.Error();
                result.ResultError = loginResult.ResultError;
                return(result);
            }
        }
コード例 #5
0
        /// <summary>
        /// 描述:家校登陆
        /// <para>作    者:蔡亚康</para>
        /// <para>创建时间:2019-03-06</para>
        /// </summary>
        /// <param name="request">用户登陆的手机号和验证码等信息</param>
        /// <exception>
        /// 异常ID:2->手机号码在系统不存在
        /// 异常ID:1->验证码有误
        /// 异常ID:6->微信号已被其他手机号绑定
        /// 异常ID:7->用户信息数据解密失败
        /// </exception>
        /// <returns>登陆结果</returns>
        public StudentLoginResponse SignIn(StudentLoginRequest request)
        {
            TblHssPassport       passport = _repository.Value.GetByUserCode(request.Mobile);
            StudentLoginResponse result   = new StudentLoginResponse();

            //1、验证账户是否存在
            this.ValidateUserExist(passport);

            //2、短信验证码校验
            this.ValidateSmsCode(request.Mobile, request.SmsCode);

            //3、获取openid
            Code2SessionService wxService = new Code2SessionService();
            OpenIdResponse      openid    = wxService.GetOpenId(request.WxCode);


            //4、检查openid是否已经被其他手机号绑定
            TblHssPassport passport2 = _repository.Value.GetByOpenId(openid.OpenId);

            if (passport2 != null && passport2.OpenId == openid.OpenId && passport2.UserCode != request.Mobile)
            {
                throw new BussinessException(ModelType.Hss, 6);
            }

            //5、用户数据解密
            try
            {
                string  data       = AESHelper.AESDecrypt(request.EncryptedData, openid.Session_Key, request.Iv);
                JObject wxUserInfo = (JObject)JsonConvert.DeserializeObject(data);

                //检查返回值是否包含unionID,防止出现异常。
                JToken jtoke = null;
                if (wxUserInfo.TryGetValue("unionId", out jtoke))
                {
                    passport.UnionId = jtoke.ToString();
                }
                else
                {
                    LogWriter.Write(this, "解密数据没有unionID,原数据如下:" + GetDecryptData(request, openid), LoggerType.Warn);
                }
            }
            catch (Exception ex)
            {
                LogWriter.Write(this, "小程序解密失败,原数据如下:" + GetDecryptData(request, openid), LoggerType.Error);
                throw new BussinessException(ModelType.Hss, 7);
            }
            //获取到的unionID为空,有可能是用户未允许访问授权
            if (string.IsNullOrEmpty(passport.UnionId))
            {
                throw new BussinessException(ModelType.Hss, 8);
            }

            //6、绑定openid 并更新最新登陆信息,包括最新的openid
            passport.OpenId           = openid.OpenId;//openid.OpenId;   //如果在另外一个微信上登陆将会被新的替换
            passport.LastLoginIp      = passport.CurrentLoginIp;
            passport.LastLoginDate    = passport.CurrentLoginDate;
            passport.CurrentLoginIp   = request.IpAddress;
            passport.CurrentLoginDate = DateTime.Now;
            passport.LoginTimes       = passport.LoginTimes + 1;
            _repository.Value.Update(passport);

            //6、记录登陆日记
            AddOperationLog(passport);

            //7、返回登陆结果
            JwtTokenService tokenService = new JwtTokenService();

            result.Token = tokenService.CreateToken(passport);

            return(result);
        }
コード例 #6
0
 public StudentLoginResponse SignIn([FromBody] StudentLoginRequest request)
 {
     request.IpAddress = "";
     return(new AuthenicationService().SignIn(request));
 }