public string login(string username, string password, string code, string uuid, RequestBasicInfo info)
        {
            string verifyKey = YouGeSystemConst.CAPTCHA_CODE_KEY + uuid;

            string captcha = YouGeRedisHelper.Get(verifyKey);

            YouGeRedisHelper.Del(verifyKey);
            if (captcha == null)
            {
                //启动线程 记录日志
                var ta = new Task(() =>

                                  sysLoginRepository.recordLogininfor(username, YouGeSystemConst.FAIL, "没有验证码", info)
                                  );
                ta.Start();

                throw new CaptchaExpireException();
            }

            if (!string.Equals(code, captcha, StringComparison.OrdinalIgnoreCase))
            {
                var tb = new Task(() =>
                                  sysLoginRepository.recordLogininfor(username, YouGeSystemConst.FAIL, "验证码已失效", info)
                                  );
                tb.Start();
                throw new CaptchaException();
            }
            try
            {
                LoginUser loginUser = this.loadUserByUsername(username, password);
                var       tf        = new Task(() =>
                                               sysLoginRepository.recordLogininfor(username, YouGeSystemConst.SUCCESS, "登录成功", info)
                                               );
                tf.Start();
                // 生成token
                return(tokenService.createToken(loginUser, info));
            }
            catch (Exception e)
            {
                if (e.Message.Contains("密码错误"))
                {
                    var tc = new Task(() =>
                                      sysLoginRepository.recordLogininfor(username, YouGeSystemConst.FAIL, "用户不存在/密码错误", info)
                                      );
                    tc.Start();


                    throw new UserPasswordNotMatchException();
                }
                else
                {
                    var td = new Task(() =>
                                      sysLoginRepository.recordLogininfor(username, YouGeSystemConst.FAIL, e.Message, info)
                                      );
                    td.Start();

                    throw new CustomException(e.Message);
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        public void clearCache()
        {
            string keys = YouGeSystemConst.SYS_CONFIG_KEY + "*";

            YouGeRedisHelper.Del(keys);
            // throw new NotImplementedException();
        }
        public AjaxReponseBase getCode()
        {
            // 生成随机字串
            string verifyCode = string.Empty;
            // 唯一标识
            string uuid      = Guid.NewGuid().ToString().Replace("-", "");
            string verifyKey = YouGeSystemConst.CAPTCHA_CODE_KEY + uuid;


            // 生成图片
            int          w = 111, h = 36;
            MemoryStream stream = new MemoryStream();

            stream = VerifyCodeUtils.outputImage(w, h, out verifyCode, 4);
            YouGeRedisHelper.Set(verifyKey, verifyCode, YouGeSystemConst.CAPTCHA_EXPIRATION * 60);
            try
            {
                AjaxReponseBase ajax = AjaxReponseBase.Success();
                ajax.Add("uuid", uuid);
                ajax.Add("verifyCode", verifyCode);
                byte[] A = stream.ToByteArray();
                stream.Close();
                ajax.Add("img", YouGeBase64.encode(A));
                return(ajax);
            }
            catch (Exception e)
            {
                Log4NetHelper.Error("获取验证码异常 " + e.StackTrace);
                return(AjaxReponseBase.Error(e.Message));
            }
            finally
            {
                stream.Close();
            }
        }
 public void delLoginUser(string token)
 {
     if (!string.IsNullOrEmpty(token))
     {
         string userKey = getTokenKey(token);
         YouGeRedisHelper.Del(userKey);
     }
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="config"></param>
        /// <returns></returns>
        public int insertConfig(SysConfig config)
        {
            int row = this.Add(config);

            if (row > 0)
            {
                YouGeRedisHelper.Set(config.ConfigKey, config.ConfigValue);
            }
            return(row);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="config"></param>
        /// <returns></returns>
        public int updateConfig(SysConfig config)
        {
            int row = this.Edit(config);

            if (row > 0)
            {
                YouGeRedisHelper.Set(config.ConfigKey, config.ConfigValue);
            }
            return(row);
        }
        public void refreshToken(LoginUser loginUser)
        {
            loginUser.loginTime = DateTimeExtensions.CurrentTimeMillis();
            int expireTime = 30; // TO DO 这个要写在appsettiong.json文件中

            loginUser.expireTime = loginUser.loginTime + expireTime * MILLIS_MINUTE;
            // 根据uuid将loginUser缓存
            string userKey = getTokenKey(loginUser.token);

            YouGeRedisHelper.Set(userKey, loginUser, expireTime * 60);
        }
        public LoginUser getLoginUser(HttpRequest request)
        {
            // 获取请求携带的令牌
            string token = getToken(request);

            if (!string.IsNullOrEmpty(token))
            {
                List <Claim> claims = parseToken(token);
                // 解析对应的权限以及用户信息\
                string uuid = claims.Where(U => U.Type == YouGeSystemConst.LOGIN_USER_KEY).FirstOrDefault().Value;
                // string uuid = (string)claims.get();
                string    userKey = getTokenKey(uuid);
                LoginUser user    = YouGeRedisHelper.Get <LoginUser>(userKey);
                return(user);
            }
            return(null);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="configIds"></param>
        /// <returns></returns>
        public int deleteConfigByIds(long[] configIds)
        {
            int row = 0, count = 0;

            string[] keys = new string[configIds.Length];
            for (int i = 0; i < configIds.Length; i++)
            {
                row     = this.Delete((int)configIds[i]);
                count   = count + row;
                keys[i] = configIds[i].ToString();
            }


            if (count > 0)
            {
                YouGeRedisHelper.Del(keys);
                //  List<String> keys = YouGeRedisHelper.get(YouGeSystemConst.SYS_CONFIG_KEY + "*");
                // redisCache.deleteObject(keys);
            }
            return(count);
        }
Esempio n. 10
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddControllers().AddNewtonsoftJson(options =>
            {
                //修改属性名称的序列化方式,首字母小写
                options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

                //修改时间的序列化方式
                options.SerializerSettings.Converters.Add(new IsoDateTimeConverter()
                {
                    DateTimeFormat = "yyyy-MM-dd HH:mm:ss"
                });
                options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; //设置忽略值
            }
                                                        );
            services.BuildAutofacServiceProvider();
            #region swagger ui
            //使用自身的
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                    ValidateLifetime         = false,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = "jonny",
                    ValidAudience    = "jonny",
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("secretsecretsecret"))
                };
            });

            //使用identityserver

            //services.AddAuthentication("Bearer")
            //   .AddJwtBearer("Bearer", options =>
            //   {
            //       options.Authority = "http://localhost:5000";
            //       options.RequireHttpsMetadata = false;
            //       options.Audience = "user_api";
            //   });


            services.AddSwaggerGen(options =>
            {
                var scheme = new OpenApiSecurityScheme()
                {
                    Scheme       = JwtBearerDefaults.AuthenticationScheme,
                    BearerFormat = "JWT",
                    In           = ParameterLocation.Header,
                    //头名称
                    Name = "Authorization", //这个不能动,一定要一幕一样
                    Type = SecuritySchemeType.ApiKey,

                    Description = "Bearer (Token) Bearer {token}注意有空格 "
                };
                options.AddSecurityDefinition(JwtBearerDefaults.AuthenticationScheme, scheme);
                options.AddSecurityRequirement(new OpenApiSecurityRequirement()
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "Bearer"
                            }
                        },
                        new string[] {}
                    }
                });
                options.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "有个 Core", Version = "v1"
                });
                //xml 文件
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                // xml
                var xmlPath = System.IO.Path.Combine(AppContext.BaseDirectory, xmlFile);
                options.IncludeXmlComments(xmlPath, true);
            });
            #endregion

            // eg 1.单个redis实现 普通模式
            //CSRedisClient csredis = new CSRedisClient("127.0.0.1:6379,password=,defaultDatabase=csredis,prefix=csredis-example");
            //eg 2.单个redis,使用appsettings.json中的配置项
            IConfigurationSection configurationSection = Configuration.GetSection("CsRedisConfig:DefaultConnectString");
            CSRedisClient         csredis = new CSRedisClient(configurationSection.Value);
            //初始化 RedisHelper
            YouGeRedisHelper.Initialization(csredis);
            //注册mvc分布式缓存
            services.AddSingleton <IDistributedCache>(new CSRedisCache(RedisHelper.Instance));
            services.Configure <YouGeDbContextOption>(options =>
            {
                options.TagName           = "db2";
                options.ConnectionString  = Configuration.GetConnectionString("YouGeDB");
                options.ModelAssemblyName = "YouGe.Core.DBEntitys";    //这里必须是数据库实体类所在的项目
                options.IsOutputSql       = false;
            }
                                                      );
            //services.AddDbContext<IYouGeDbContext, YouGeDbContext>(option => { },ServiceLifetime.Scoped ); //注入EF上下文
            services.AddDbContext <IYouGeDbContext, YouGeDbContext>(); //注入EF上下文
        }