//创建考试 public static object postExam(string token, object json) { try { int user_id = JwtManager.DecodeToken(token); NBackendContext ctx = new NBackendContext(); //验证该用户是否是教学的老师 User user = UserBiz.getUserById(ctx, user_id); if (user == null || user.role != "teacher_edu") { return(Helper.JsonConverter.Error(400, "该用户没有权限创建试卷")); } //var body = Helper.JsonConverter.Decode(json); var body = JsonConvert.DeserializeObject <Dictionary <string, object> >(json.ToString()); int sec_id = (int)(long)body["sec_id"]; int course_id = (int)(long)body["course_id"]; string semester = (string)body["semester"]; int year = (int)(long)body["year"]; string scope = (string)body["scope"]; string type = (string)body["type"]; string start_time = (string)body["start_time"]; string end_time = (string)body["end_time"]; string title = (string)body["title"]; //NBackendContext ctx = new NBackendContext(); //创建考试第一步 Exam exam = new Exam { secId = sec_id, courseId = course_id, semester = semester, year = year, scope = scope, type = type2Id(type), start_time = start_time, end_time = end_time, title = title, }; ctx.Exams.Add(exam); var questions = (JArray)body["questions"]; foreach (var qu in questions) { IDictionary <string, JToken> rates = (JObject)qu; // Explicit typing just for "proof" here Dictionary <string, object> __body = rates.ToDictionary(pair => pair.Key, pair => (object)pair.Value); int question_id = ((JValue)__body["question_id"]).Value <int>(); int single_score = ((JValue)__body["score"]).Value <int>(); int index = ((JValue)__body["index"]).Value <int>(); //if (questions.Select(_qu=>_qu.).Contains(question_id)) //{ ctx.ExamQuestions.Add(new ExamQuestion { examId = exam.ExamId, questionId = question_id, score = single_score, index = index, }); //} //else //{ // //有一道题找不到? //} } //创建考试第二步 //int exam_id = exam.ExamId; //string _quess = body["questions"]; //var quess = JsonConvert.DeserializeObject<List<object>>(_quess); //var questions = ctx.Questions.Select(qu => qu.QuestionId).ToList(); //foreach (object obj in quess) //{ // var _body = Helper.JsonConverter.Decode(obj); // int question_id = int.Parse(_body["question_id"]); // int single_score = int.Parse(_body["score"]); // int index = int.Parse(_body["index"]); // if (questions.Contains(question_id)) // { // ctx.ExamQuestions.Add(new ExamQuestion // { // examId = exam_id, // questionId = question_id, // score = single_score, // index = index, // }); // } // else // { // //有一道题找不到? // } //} ctx.SaveChanges(); var data = new { //exam_id }; return(Helper.JsonConverter.BuildResult(data)); } catch (Exception e) { return(Helper.JsonConverter.Error(400, "创建考试时出错")); } }
public async Task <IHttpActionResult> ObtenerHtml(ExperianViewModels experian) { try { experian.documentType = "1"; experian.password = WebConfigurationManager.AppSettings["Experian_Password"].ToString(); experian.username = WebConfigurationManager.AppSettings["Experian_User"].ToString(); experian.grant_type = WebConfigurationManager.AppSettings["Experian_Gran_Type"].ToString(); var idUser = JwtManager.getIdUserSession(); var Usuario = await _ir.Find <Usuario>(idUser); var fun = new FuncionesViewModels(); var token = ""; //var respuesta = null; var user = await _ir.GetFirst <Usuario>(z => z.identificacion == Usuario.identificacion); if (user != null && !String.IsNullOrEmpty(user.responseDataExperian)) { // Fecha Auxiliar DateTime now = DateTime.Now; // Sumamos 1 mes a la fecha guardada DateTime date = user.fechaAccesoExperian.GetValueOrDefault().AddMonths(1); // Comparamos la fecha modificada, si es menor significa que ya pasó un mes y hay // que hacer la petición si no retorna lo que está almacenado if (date < now) { JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); string urlFuente = ""; string fuente = ""; string color = ""; string enlace = ""; var id = Convert.ToInt32(WebConfigurationManager.AppSettings["Id_Html"].ToString()); var htmlData = WebConfigurationManager.AppSettings["HtmlExperian"]; //var htmlData = await _ir.GetFirst<Parametros>(z => z.idParametro == id); if (htmlData != null) { dynamic j = jsonSerializer.Deserialize <dynamic>(htmlData);//deserializamos el objeto urlFuente = j["urlFuente"].ToString(); fuente = j["fuente"].ToString(); color = j["color"].ToString(); enlace = j["enlaceDiagnostico"].ToString(); } token = fun.TokenDataExperian(experian); var respuesta = fun.HtmlDataExperian(experian, token); respuesta.scoreHTML = respuesta.scoreHTML.Replace("{{urlFuente}}", urlFuente).Replace("{{fuente}}", fuente).Replace("{{color}}", color) .Replace("{{enlaceDiagnostico}}", enlace); respuesta.diagnoseHTML = respuesta.diagnoseHTML.Replace("{{urlFuente}}", urlFuente).Replace("{{fuente}}", fuente).Replace("{{color}}", color) .Replace("{{enlaceDiagnostico}}", enlace); //object respuesta = null; var t = await _ir.GetFirst <Usuario>(z => z.identificacion == experian.document); if (t != null) { t.responseDataExperian = jsonSerializer.Serialize(respuesta); t.fechaAccesoExperian = DateTime.Now; await _ir.Update(t, t.idUsuario); } return(Ok(respuesta)); } else { var data = JsonConvert.DeserializeObject(user.responseDataExperian); return(Ok(data)); } } else { JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); string urlFuente = ""; string fuente = ""; string color = ""; string enlace = ""; var id = Convert.ToInt32(WebConfigurationManager.AppSettings["Id_Html"].ToString()); var htmlData = WebConfigurationManager.AppSettings["HtmlExperian"]; if (htmlData != null) { dynamic j = jsonSerializer.Deserialize <dynamic>(htmlData);//deserializamos el objeto urlFuente = j["urlFuente"].ToString(); fuente = j["fuente"].ToString(); color = j["color"].ToString(); enlace = j["enlaceDiagnostico"].ToString(); } token = fun.TokenDataExperian(experian); var respuesta = fun.HtmlDataExperian(experian, token); respuesta.scoreHTML = respuesta.scoreHTML.Replace("{{urlFuente}}", urlFuente).Replace("{{fuente}}", fuente).Replace("{{color}}", color) .Replace("{{enlaceDiagnostico}}", enlace); respuesta.diagnoseHTML = respuesta.diagnoseHTML.Replace("{{urlFuente}}", urlFuente).Replace("{{fuente}}", fuente).Replace("{{color}}", color) .Replace("{{enlaceDiagnostico}}", enlace); //object respuesta = null; var t = await _ir.GetFirst <Usuario>(z => z.identificacion == experian.document); if (t != null) { t.responseDataExperian = jsonSerializer.Serialize(respuesta); t.fechaAccesoExperian = DateTime.Now; await _ir.Update(t, t.idUsuario); } return(Ok(respuesta)); } } catch (Exception ex) { return(BadRequest(ex.Message)); } }
public TokenController(JwtManager manager) { this.manager = manager; }
private static void ConfigureAutoMapper() { Mapper.Initialize(cfg => { cfg.CreateMap <User, UserReturnModel>() .ForMember("Id", opt => opt.MapFrom(src => src.Id)) .ForMember("UserName", opt => opt.MapFrom(src => src.UserName)) .ForMember("Email", opt => opt.MapFrom(src => src.Email)) .ForMember("FirstName", opt => opt.MapFrom(src => src.FirstName)) .ForMember("LastName", opt => opt.MapFrom(src => src.LastName)) .ForMember("Sex", opt => opt.MapFrom(t => (t.Sex == SexEnum.Male ? "Male" : (t.Sex == SexEnum.Female ? "Female" : "Unknown")))) .ForMember("BirthDate", opt => opt.MapFrom(t => t.BirthDate.Date.ToString("yyyy-MM-dd"))) .ForMember("AvatarUrl", opt => opt.MapFrom(t => t.AvatarUrl ?? HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + @"/Avatars/default_avatar.png")); cfg.CreateMap <User, UserReturnModelWithToken>() .ForMember("Token", opt => opt.MapFrom(t => JwtManager.GenerateToken(t.UserName, t.PasswordHash, 12))) .ForMember("Id", opt => opt.MapFrom(src => src.Id)) .ForMember("UserName", opt => opt.MapFrom(src => src.UserName)) .ForMember("Email", opt => opt.MapFrom(src => src.Email)) .ForMember("FirstName", opt => opt.MapFrom(src => src.FirstName)) .ForMember("LastName", opt => opt.MapFrom(src => src.LastName)) .ForMember("Sex", opt => opt.MapFrom(t => (t.Sex == SexEnum.Male ? "Male" : (t.Sex == SexEnum.Female ? "Female" : "Unknown")))) .ForMember("BirthDate", opt => opt.MapFrom(t => t.BirthDate.Date.ToString("yyyy-MM-dd"))) .ForMember("AvatarUrl", opt => opt.MapFrom(t => t.AvatarUrl ?? HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + @"/Avatars/default_avatar.png")); cfg.CreateMap <CreateUserBindingModel, User>() .ForMember("PasswordHash", opt => opt.MapFrom(t => PasswordEncoder.Encode(t.Password))) .ForMember("AvatarUrl", opt => opt.MapFrom(t => "https://robohash.org/" + t.UserName)) .ForMember("Sex", opt => opt.MapFrom(t => (t.Sex == "Male" ? SexEnum.Male: (t.Sex == "Female" ? SexEnum.Female : SexEnum.Unknown)))); cfg.CreateMap <Message, MessageReturnModel>() .ForMember("Id", opt => opt.MapFrom(src => src.Id)) .ForMember("Text", opt => opt.MapFrom(src => src.Text)) .ForMember("FirstName", opt => opt.MapFrom(src => src.Sender.FirstName)) .ForMember("DateTime", opt => opt.MapFrom(t => t.DateTime .ToString("MM/dd/yyyy HH:mm:ss"))); cfg.CreateMap <Message, ConversationReturnModel>() .ForMember("Text", opt => opt.MapFrom(src => src.Text)) .ForMember("DateTime", opt => opt.MapFrom(t => t.DateTime .ToString("MM/dd/yyyy HH:mm:ss"))) .ForMember("OtherUserId", opt => opt.ResolveUsing((source, dest, arg3, arg4) => ((User)arg4.Options.Items["User"]).Id)) .ForMember("FirstName", opt => opt.ResolveUsing((source, dest, arg3, arg4) => ((User)arg4.Options.Items["User"]).FirstName)) .ForMember("LastName", opt => opt.ResolveUsing((source, dest, arg3, arg4) => ((User)arg4.Options.Items["User"]).LastName)) .ForMember("AvatarUrl", opt => opt.ResolveUsing((source, dest, arg3, arg4) => ((User)arg4.Options.Items["User"]).AvatarUrl)) .ForMember("NewMessagesCount", opt => opt.ResolveUsing((source, dest, arg3, arg4) => arg4.Options.Items["NewMessagesCount"])) .ForMember("Online", opt => opt.ResolveUsing((source, dest, arg3, arg4) => arg4.Options.Items["Online"])); }); }
//创建广播 public static object postBroadcast(string token, object json) { try { var body = JsonConverter.Decode(json); NBackendContext ctx = new NBackendContext(); int teacher_id = JwtManager.DecodeToken(token); User user = UserBiz.getUserById(ctx, teacher_id); if (user == null) { return(Helper.JsonConverter.Error(400, "你还没登录?")); } int type = int.Parse(body["type"]); int scope = int.Parse(body["scope"]); string start_time = body["start_time"]; string end_time = body["end_time"]; string published_time = body["published_time"]; string content = body["content"]; //k int sec_id, course_id, year; string semester; if (scope == SCOPE_CLASS) { if (!user.role.Equals("teacher_edu")) { return(Helper.JsonConverter.Error(400, "你没有权限呢")); } sec_id = int.Parse(body["sec_id"]); course_id = int.Parse(body["course_id"]); year = int.Parse(body["year"]); semester = body["semester"]; } else { if (!user.role.Equals("teacher_manage")) { return(Helper.JsonConverter.Error(400, "你没有权限呢")); } //默认班级 sec_id = 100003; course_id = 2; year = 0; semester = "Spring"; } Broadcast broadcast = new Broadcast { secId = sec_id, courseId = course_id, year = year, semester = semester, scope = scope, type = type, start_time = start_time, publish_time = published_time, end_time = end_time, content = content }; ctx.TeacherBroadcasts.Add(new TeacherBroadcast { teacherId = teacher_id, broadcastId = broadcast.BroadcastId }); ctx.Broadcasts.Add(broadcast); ValidationHelper.safeSaveChanges(ctx); var data = new { broadcast_id = broadcast.BroadcastId }; return(JsonConverter.BuildResult(data)); } catch (Exception e) { return(JsonConverter.Error(400, "创建广播失败")); } }
public async Task <JObject> PostAsync([FromBody] object value) { #region 单点登录检测 #endregion #region 注销检测 string token = JwtManager.GetRequestTokenString(Request); var redis = RedisHelper.GetRedisHelper(); if (!redis.SignInCheck(token)) { return(null);//返回错误信息提示重新登录 } #endregion #region 变量声明以及初始化 JObject regform = (JObject)value; JObject result;//返回结果 ErrorRootobject error = new ErrorRootobject { ReturnCode = "00001", msg = "JSON format error" }; string serial = JsonConvert.SerializeObject(error); //将实体类序列化为JSON字符串 result = (JObject)JsonConvert.DeserializeObject(serial); //将JSON字符串反序列化为JObject对象 string acToken = "token"; string email = "email"; string phonenum = "phonenum"; string sex = "sex"; string username = "******"; #endregion #region 检查表单 try { acToken = regform["AccessToken"].ToString(); email = regform["Email"].ToString(); phonenum = regform["Phonenum"].ToString(); sex = regform["Sex"].ToString(); } catch (Exception) { error.ReturnCode = "0009"; error.msg = "JSON format error"; serial = JsonConvert.SerializeObject(error); //将实体类序列化为JSON字符串 result = (JObject)JsonConvert.DeserializeObject(serial); //将JSON字符串反序列化为JObject对象 return(result); } #endregion #region 排查危险字符 ; bool emailCheck = Regex.IsMatch(email, @"^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$"); //检查邮箱格式 bool phonnumCheck = Regex.IsMatch(phonenum, @"^1[3|4|5|7|8][0-9]{9}$"); //检查手机号格式 bool sexCheck = Regex.IsMatch(sex, @"[-|;|,|\/|||||\}|\{|%|@|\*|!|\']"); bool tokenCheck = Regex.IsMatch(acToken, @"[|;|,|\/|||||\}|\{|%|@|\*|!|\']"); bool[] check = { emailCheck, phonnumCheck, sexCheck, tokenCheck }; List <KeyValuePair <String, Boolean> > paraList = new List <KeyValuePair <string, bool> > { new KeyValuePair <string, bool>("1003", tokenCheck), new KeyValuePair <string, bool>("0006", emailCheck), new KeyValuePair <string, bool>("0011", sexCheck), }; foreach (var i in paraList) { if (i.Value) { //失败后返回错误原因: error = new ErrorRootobject { ReturnCode = i.Key, msg = " contains dangerous characters " }; serial = JsonConvert.SerializeObject(error); //将实体类序列化 为JSON字符串 result = (JObject)JsonConvert.DeserializeObject(serial); //将JSON字符串反序列化为JObject对象 return(result); } } #endregion #region 检查Token var conn = anJiaContext.Database.GetDbConnection(); conn.Open(); var command = conn.CreateCommand(); string query = "SELECT Username " + "FROM Users " + "WHERE AccessToken = '" + acToken + "'"; //command.CommandText = query; //try //{ // DbDataReader unameReader = await command.ExecuteReaderAsync(); // unameReader.Read(); // username = unameReader["Username"].ToString(); // conn.Close(); //} //catch (Exception) //{ // error = new ErrorRootobject // { // error_code = "1004", // msg = " Token does not exist " // }; // serial = JsonConvert.SerializeObject(error);//将实体类序列化 为JSON字符串 // result = (JObject)JsonConvert.DeserializeObject(serial);//将JSON字符串反序列化为JObject对象 conn.Close(); // return result; //} var claimsPrincipal = JwtManager.GetPrincipal(acToken); string name = "null"; if (claimsPrincipal != null) { name = claimsPrincipal.Identity.Name.ToString(); } else { error = new ErrorRootobject { ReturnCode = "0012", msg = "Token Expire" //令牌过期 }; serial = JsonConvert.SerializeObject(error); //将实体类序列化 为JSON字符串 result = (JObject)JsonConvert.DeserializeObject(serial); //将JSON字符串反序列化为JObject对象 return(result); } #endregion #region 更新信息 command = conn.CreateCommand(); conn.Open(); query = "UPDATE Users " + " SET email = '" + email + "', " + " phonenum = '" + phonenum + "', " + " Sex = '" + sex + "' " + " WHERE Username = '******'"; command.CommandText = query; try { DbDataReader BindingReader = await command.ExecuteReaderAsync(); error = new ErrorRootobject { ReturnCode = "0000", msg = "Update success" }; serial = JsonConvert.SerializeObject(error); //将实体类序列化 为JSON字符串 result = (JObject)JsonConvert.DeserializeObject(serial); //将JSON字符串反序列化为JObject对象 conn.Close(); BindingReader.Dispose(); //释放资源 } catch (Exception) { //绑定失败 error = new ErrorRootobject { ReturnCode = "0012", msg = "Update failed" }; serial = JsonConvert.SerializeObject(error); //将实体类序列化 为JSON字符串 result = (JObject)JsonConvert.DeserializeObject(serial); //将JSON字符串反序列化为JObject对象 conn.Close(); } #endregion return(result); }
public AuthorizeAttribute(JwtManager jwtManager, ITokenRepository tokenRepository) { _jwtManager = jwtManager; _tokenRepository = tokenRepository; }
public UsersController(UserService <User> userService, JwtManager jwtManager) { _userService = userService; _jwtManager = jwtManager; }
public UsersController(IUserService userService, JwtManager jwtManager, IAuthenticationService authService) { this.userService = userService; this.jwtManager = jwtManager; this.authService = authService; }
//删除、修改、提交题目全靠它 private static object questionHelper(string token, object json, int option) { int user_id = JwtManager.DecodeToken(token); NBackendContext ctx = new NBackendContext(); User user = UserBiz.getUserById(ctx, user_id); if (user == null || !user.role.Equals("teacher_edu")) { //可以再判断这个老师是不是教这个的 return(Helper.JsonConverter.Error(400, "您未登录或者没有权限")); } var body = Helper.JsonConverter.Decode(json); try { //删除、修改、提交题目分发逻辑 switch (option) { default: { int course_id = int.Parse(body["course_id"]); string chapter = body["chapter"]; string content = body["content"]; string options = body["options"]; string answer = body["answer"]; if (option == POST) { var newq = new Question { courseId = course_id, chapter = chapter, content = content, options = options, answer = answer, }; ctx.Questions.Add(newq); ctx.SaveChanges(); object data = new { question_id = newq.QuestionId }; return(Helper.JsonConverter.BuildResult(data)); } else if (option == PUT) { int question_id = int.Parse(body["question_id"]); var q = ctx.Questions.Where(qu => qu.QuestionId == question_id); if (!q.Any()) { return(Helper.JsonConverter.Error(400, "没有这道题")); } else { Question question = q.Single(); question.answer = answer; question.chapter = chapter; question.options = options; question.content = content; ctx.SaveChanges(); } } return(Helper.JsonConverter.BuildResult(null)); } case DELETE: { int question_id = int.Parse(body["question_id"]); var q = ctx.Questions.Where(qu => qu.QuestionId == question_id); if (!q.Any()) { return(Helper.JsonConverter.Error(400, "没有这道题")); } else { var qu = q.Single(); ctx.Questions.Remove(qu); ctx.SaveChanges(); } return(Helper.JsonConverter.BuildResult(null)); //break; } } } catch (Exception e) { return(Helper.JsonConverter.Error(400, "请检查您的提交信息")); } }
public void TryAndGetClaimsPrincipalWithNoToken() { var principal = JwtManager.GetPrincipal(null); Assert.That(principal, Is.Null); }
//获取某张试卷所有的题目,包括学生考试前后和老师查看 public static object getQuestionsOfExam(string token, object json) { try { var body = Helper.JsonConverter.Decode(json); int user_id = JwtManager.DecodeToken(token); int exam_id = int.Parse(body["exam_id"]); NBackendContext ctx = new NBackendContext(); //连接考试表和试题表 var q = ctx.Exams.Join(ctx.ExamQuestions, _exam => _exam.ExamId, eq => eq.examId, (_exam, eq) => eq ).Join(ctx.Questions, eq => eq.questionId, ques => ques.QuestionId, (eq, ques) => ques ); //该试卷的所有题目 var quess = q.ToList(); User user = UserBiz.getUserById(ctx, user_id); if (!quess.Any()) { return(Helper.JsonConverter.Error(400, "不是考试没了就是题库崩了?")); } Exam exam = getExamById(ctx, exam_id); string title = exam.title; string start_time = exam.start_time; string end_time = exam.end_time; var q1 = ctx.ExamQuestions.Where(e => e.examId == exam.ExamId).Join(ctx.Questions, ex => ex.questionId, qu => qu.QuestionId, (ex, qu) => qu ); var questions = q1.ToList(); object data = null; List <object> qdata = new List <object>(); if (user.role.Equals("teacher_edu")) { foreach (var qu in questions) { int index = getQuestionIndex(ctx, exam_id, qu.QuestionId); int score = getScoreById(ctx, qu.QuestionId, exam_id); qdata.Add(new { question_id = qu.QuestionId, course_id = qu.courseId, chapter = qu.chapter, content = qu.content, options = qu.options, answer = qu.answer, index, score }); data = new { questions = qdata, title = title, }; } } else if (user.role.Equals("student")) { var q2 = ctx.TakesExams.Where(te => te.StudentId == user_id && te.ExamId == exam_id ); //if (!q2.Any()) //{ // return Helper.JsonConverter.Error(400, "无效用户或考试"); //} //var ex = q2.Single().Exam; var ex = getExamById(ctx, exam_id); if (ex == null) { return(Helper.JsonConverter.Error(400, "考试没了!")); } bool exam_ended = isExamFinished(ex); //没参加过这场考试并且没超时 if (!q2.Any() && !exam_ended) { foreach (var qu in questions) { int index = getQuestionIndex(ctx, exam_id, qu.QuestionId); int score = getScoreById(ctx, qu.QuestionId, exam_id); qdata.Add(new { question_id = qu.QuestionId, course_id = qu.courseId, chapter = qu.chapter, content = qu.content, options = qu.options, index, score, }); } data = new { questions = qdata, title = title, start_time = start_time, end_time = end_time, exam_status = false, }; } else { foreach (var qu in questions) { int index = getQuestionIndex(ctx, exam_id, qu.QuestionId); int score = getScoreById(ctx, qu.QuestionId, exam_id); qdata.Add(new { question_id = qu.QuestionId, course_id = qu.courseId, chapter = qu.chapter, content = qu.content, options = qu.options, answer = qu.answer, index, score }); } data = new { questions = qdata, title = title, start_time = start_time, end_time = end_time, exam_status = true, total_score = q2.Single().score }; } } else { return(Helper.JsonConverter.Error(400, "您没有权限(^U^)ノ~YO")); } return(Helper.JsonConverter.BuildResult(data)); } catch (Exception e) { return(Helper.JsonConverter.Error(400, "题目信息获取出错,请检查对应字段")); } }
public static object examSumup(string token) { try { int user_id = JwtManager.DecodeToken(token); NBackendContext ctx = new NBackendContext(); User user = UserBiz.getUserById(ctx, user_id); //参加的考试 var qexam_taken = ctx.TakesExams.Where(te => te.Student.StudentId == user_id).ToList(); //参加的课程的所有考试 var qexam_all = ctx.Takes.Where(take => take.StudentId == user_id).Join(ctx.Exams, take => new { take.Section.SecId, take.Section.courseId }, exam => new { exam.Section.SecId, exam.Section.courseId } , (take, exam) => new { exam, take.Section } ).Where(exam_sec => exam_sec.exam.Section.year == exam_sec.Section.year && exam_sec.exam.Section.semester == exam_sec.Section.semester).ToList() .Select(te => te.exam).ToList(); //没参加的考试成绩为0 var qexam_not_taken = qexam_all.Except(qexam_taken.Select(qt => qt.Exam)).ToList(); int exam_num = qexam_all.Count(); List <object> exams = new List <object>(); foreach (var et in qexam_taken) { int grade = 1;//等级 Course course = et.Exam.Course; int score = getTotalScore(ctx, et.ExamId); if (score == 0) { return(Helper.JsonConverter.Error(404, "找不到这张试卷")); } grade = (int)((float)et.score * 5 / score); exams.Add(new { exam_id = et.ExamId, course.course_name, et.Exam.title, grade }); } foreach (var ent in qexam_not_taken) { Course course = ent.Course; exams.Add(new { exam_id = ent.ExamId, course.course_name, ent.title, grade = 1 }); } var data = new { exam_num, exams }; return(Helper.JsonConverter.BuildResult(data)); } catch (Exception e) { return(Helper.JsonConverter.Error(400, "查看总结出错,请检查请求字段")); } }
public static bool validateToken(int user_id, string token) { return(user_id == JwtManager.DecodeToken(token)); }
public ActionResult GetFileTypeMapping() { FileClientService fileClientService = new FileClientService(fileServiceUrl, JwtManager.GetAuthorization(Request)); var mappings = fileClientService.GetExtensionMap(); return(Content(JsonSerializerHelper.Serialize(mappings))); }
public AuthController(JwtManager manager) { this.manager = manager; }
/// <summary> /// The method is to convert the file to the required format /// </summary> /// <param name="documentUri">Uri for the document to convert</param> /// <param name="fromExtension">Document extension</param> /// <param name="toExtension">Extension to which to convert</param> /// <param name="documentRevisionId">Key for caching on service</param> /// <param name="isAsync">Perform conversions asynchronously</param> /// <param name="convertedDocumentUri">Uri to the converted document</param> /// <returns>The percentage of completion of conversion</returns> /// <example> /// string convertedDocumentUri; /// GetConvertedUri("http://helpcenter.onlyoffice.com/content/GettingStarted.pdf", ".pdf", ".docx", "http://helpcenter.onlyoffice.com/content/GettingStarted.pdf", false, out convertedDocumentUri); /// </example> /// <exception> /// </exception> public static int GetConvertedUri(string documentUri, string fromExtension, string toExtension, string documentRevisionId, bool isAsync, out string convertedDocumentUri) { convertedDocumentUri = string.Empty; fromExtension = string.IsNullOrEmpty(fromExtension) ? Path.GetExtension(documentUri) : fromExtension; var title = Path.GetFileName(documentUri); title = string.IsNullOrEmpty(title) ? Guid.NewGuid().ToString() : title; documentRevisionId = string.IsNullOrEmpty(documentRevisionId) ? documentUri : documentRevisionId; documentRevisionId = GenerateRevisionId(documentRevisionId); var request = (HttpWebRequest)WebRequest.Create(DocumentConverterUrl); request.Method = "POST"; request.ContentType = "application/json"; request.Accept = "application/json"; request.Timeout = ConvertTimeout; var body = new Dictionary <string, object>() { { "async", isAsync }, { "filetype", fromExtension.Trim('.') }, { "key", documentRevisionId }, { "outputtype", toExtension.Trim('.') }, { "title", title }, { "url", documentUri } }; if (JwtManager.Enabled) { var payload = new Dictionary <string, object> { { "payload", body } }; var payloadToken = JwtManager.Encode(payload); var bodyToken = JwtManager.Encode(body); request.Headers.Add("Authorization", "Bearer " + payloadToken); body.Add("token", bodyToken); } var bytes = Encoding.UTF8.GetBytes(new JavaScriptSerializer().Serialize(body)); request.ContentLength = bytes.Length; using (var requestStream = request.GetRequestStream()) { requestStream.Write(bytes, 0, bytes.Length); } // hack. http://ubuntuforums.org/showthread.php?t=1841740 if (_Default.IsMono) { ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true; } string dataResponse; using (var response = request.GetResponse()) using (var stream = response.GetResponseStream()) { if (stream == null) { throw new Exception("Response is null"); } using (var reader = new StreamReader(stream)) { dataResponse = reader.ReadToEnd(); } } return(GetResponseUri(dataResponse, out convertedDocumentUri)); }
public ActionResult Upload(HttpPostedFileBase file) { FileClientService fileClientService = new FileClientService(fileServiceUrl, JwtManager.GetAuthorization(Request)); var result = fileClientService.Upload(file.FileName, file.ContentType, file.InputStream); if (result.code != 0) { return(new ResponseModel <string>(ErrorCode.server_exception, result.message)); } if (user.UpdateFileId(User.Identity.Name, result.result.FileId, result.result.FileName) > 0) { return(new ResponseModel <string>(ErrorCode.success, result.result.FileId)); } else { return(new ResponseModel <string>(ErrorCode.server_exception, "")); } }
public AuthenticationService(JwtManager jwtManager, UserManager <TUser> userManager) { this.userManager = userManager; this.jwtManager = jwtManager; }
public ActionResult Uploads(UploadFileModel uploadFileModel) { FileClientService fileClientService = new FileClientService(fileServiceUrl, JwtManager.GetAuthorization(Request)); List <UploadFileItem> files = new List <UploadFileItem>(); foreach (var item in uploadFileModel.Files) { files.Add(new UploadFileItem() { FileName = item.FileName, FileStream = item.InputStream, ContentType = item.ContentType }); } Dictionary <string, string> paras = new Dictionary <string, string>(); paras.Add("roles", uploadFileModel.Roles); paras.Add("users", uploadFileModel.Users); paras.Add("usersDisplay", uploadFileModel.UsersDisplay); var result = fileClientService.Uploads(files, paras); return(Json(result, JsonRequestBehavior.AllowGet)); }
private static void Track(HttpContext context) { var userAddress = context.Request["userAddress"]; var fileName = context.Request["fileName"]; string body; try { using (var receiveStream = context.Request.InputStream) using (var readStream = new StreamReader(receiveStream)) { body = readStream.ReadToEnd(); } } catch (Exception e) { throw new HttpException((int)HttpStatusCode.BadRequest, e.Message); } var jss = new JavaScriptSerializer(); if (string.IsNullOrEmpty(body)) { return; } var fileData = jss.Deserialize <Dictionary <string, object> >(body); if (JwtManager.Enabled) { if (fileData.ContainsKey("token")) { fileData = jss.Deserialize <Dictionary <string, object> >(JwtManager.Decode(fileData["token"].ToString())); } else if (context.Request.Headers.AllKeys.Contains("Authorization", StringComparer.InvariantCultureIgnoreCase)) { var headerToken = context.Request.Headers.Get("Authorization").Substring("Bearer ".Length); fileData = (Dictionary <string, object>)jss.Deserialize <Dictionary <string, object> >(JwtManager.Decode(headerToken))["payload"]; } else { throw new Exception("Expected JWT"); } } var status = (TrackerStatus)(int)fileData["status"]; switch (status) { case TrackerStatus.MustSave: case TrackerStatus.Corrupted: var downloadUri = (string)fileData["url"]; var saved = 1; try { var storagePath = DocManagerHelper.StoragePath(fileName, userAddress); var histDir = DocManagerHelper.HistoryDir(storagePath); var versionDir = DocManagerHelper.VersionDir(histDir, DocManagerHelper.GetFileVersion(histDir) + 1); if (!Directory.Exists(versionDir)) { Directory.CreateDirectory(versionDir); } File.Copy(storagePath, Path.Combine(versionDir, "prev" + Path.GetExtension(fileName))); DownloadToFile(downloadUri, DocManagerHelper.StoragePath(fileName, userAddress)); DownloadToFile((string)fileData["changesurl"], Path.Combine(versionDir, "diff.zip")); var hist = fileData.ContainsKey("changeshistory") ? (string)fileData["changeshistory"] : null; if (string.IsNullOrEmpty(hist) && fileData.ContainsKey("history")) { hist = jss.Serialize(fileData["history"]); } if (!string.IsNullOrEmpty(hist)) { File.WriteAllText(Path.Combine(versionDir, "changes.json"), hist); } File.WriteAllText(Path.Combine(versionDir, "key.txt"), (string)fileData["key"]); } catch (Exception) { saved = 0; } break; } context.Response.Write("{\"error\":0}"); }
public ActionResult FileState(string id) { FileClientService fileClientService = new FileClientService(fileServiceUrl, JwtManager.GetAuthorization(Request)); var fileItem = fileClientService.FileState(id); return(Json(fileItem, JsonRequestBehavior.AllowGet)); }
//[EnableCors(origins: "*", headers: "*", methods: "*")] public IHttpActionResult Post() { string usuario = String.Empty, clave = String.Empty; //error por defecto (credenciales incorrectas) (pesimista) //OWASP Secure Coding Best Practices (SBP) (#28, #33) /* 33. Authentication failure responses should not indicate which part of the authentication data was incorrect. * For example, instead of "Invalid username" or "Invalid password", just use "Invalid username and/or password" for both. * Error responses must be truly identical in both display and source code * https://www.owasp.org/index.php/OWASP_Secure_Coding_Practices_Checklist */ IHttpActionResult res = Ok(-1); //error generico por defecto (pesimista) // @ la casa bool NoSegTec = true; if (NoSegTec) { //modo desarrollo, brincarse la seguridad del TEC, usar datos alambrados //poner los datos en un oRespuesta<string> para continuar CxC.Objetos.Clases.oRespuesta <string> objResValidar = new oRespuesta <string>(); //CxC.WebApi.WCF_Seguridad.TEC_Usuario datosUsuario = (CxC.WebApi.WCF_Seguridad.TEC_Usuario)resValidar.Data; //falta calcular nombreCompleto, JWToken para retornarlo de una vez DatosUsuario datosUsuarioExt = new DatosUsuario(); datosUsuarioExt.Apellido1 = "Apellido1"; datosUsuarioExt.Apellido2 = "Apellido2"; datosUsuarioExt.Bloqueado = false; datosUsuarioExt.CorreoElectronicoANotificar = "*****@*****.**"; datosUsuarioExt.CorreoElectronicoPrincipal = "*****@*****.**"; datosUsuarioExt.Departamento = "DATIC"; datosUsuarioExt.Descripcion = ""; datosUsuarioExt.DescripPuesto = "Profesional en TI"; datosUsuarioExt.Estado = true; datosUsuarioExt.extension = "2354"; datosUsuarioExt.FechaCreacion = new DateTime(1996, 2, 7); datosUsuarioExt.FechaExpiracion = new DateTime(6155, 12, 31); datosUsuarioExt.FechaNacimiento = new DateTime(1976, 4, 20); datosUsuarioExt.IdDepartamento = 1; datosUsuarioExt.Identificacion = "109360326"; datosUsuarioExt.IdTipoUsuario = 1; datosUsuarioExt.IdUsuario = 1; datosUsuarioExt.NoCarnet = ""; datosUsuarioExt.Nombre = "Nombre"; datosUsuarioExt.OcupaCambioContrasena = false; datosUsuarioExt.Oficina = "B6"; datosUsuarioExt.TipoUsuario = "1"; datosUsuarioExt.UsuarioCreacion = "1"; datosUsuarioExt.UsuarioModificacion = "1"; datosUsuarioExt.UsuarioVencido = false; datosUsuarioExt.NombreCompleto = datosUsuarioExt.Apellido1 + " " + datosUsuarioExt.Apellido2 + " " + datosUsuarioExt.Nombre; datosUsuarioExt.Id = datosUsuarioExt.IdUsuario; datosUsuarioExt.LoginUsuario = usuario; //genera el JW Token y le pone expiración por defecto de 1 hora (esto es renovable) datosUsuarioExt.JWToken = JwtManager.GenerarToken(usuario); datosUsuarioExt.ExpiracionToken = DateTime.UtcNow.AddHours(24); //ya validó al usuario, obtiene los permisos (claims) //aca es donde ocupo obtener los permisos, luego de saber que las credenciales son válidas //TODO var consultaPermisos = ServiciosSeguridad.ConsultarPermisosUsuario(0, datosUsuario.IdUsuario, 0, 0, idUsuarioLogueado, usuarioLogueado, Utilitarios.Clases.Utilitarios.GetIpAddress(), "SessionId"); var datosPermisos = new { };// consultaPermisos.ObjetoRespuesta; var datosCompletos = new { datosUsuario = datosUsuarioExt, datosPermisos = datosPermisos }; //validación correcta del usuario y pone los datos para set retornados los datos objResValidar.CodigoRespuesta = 0; objResValidar.MensajeRespuesta = ""; objResValidar.ObjetoRespuesta = new JavaScriptSerializer().Serialize(datosCompletos); res = Ok(objResValidar); } else { try { if (Request.Headers.Contains("usuario")) { usuario = Request.Headers.GetValues("usuario").FirstOrDefault(); if (Request.Headers.Contains("clave")) { clave = Request.Headers.GetValues("clave").FirstOrDefault(); } var resValidar = ValidarUsuario(usuario, clave); //poner los datos en un oRespuesta<string> para continuar CxC.Objetos.Clases.oRespuesta <string> objResValidar = new oRespuesta <string>(); if (resValidar.Data.GetType().FullName == "CxC.WebApi.WCF_Seguridad.TEC_Usuario") { CxC.WebApi.WCF_Seguridad.TEC_Usuario datosUsuario = (CxC.WebApi.WCF_Seguridad.TEC_Usuario)resValidar.Data; //falta calcular nombreCompleto, JWToken para retornarlo de una vez DatosUsuario datosUsuarioExt = new DatosUsuario(); datosUsuarioExt.Apellido1 = datosUsuario.Apellido1; datosUsuarioExt.Apellido2 = datosUsuario.Apellido2; datosUsuarioExt.Bloqueado = datosUsuario.Bloqueado; datosUsuarioExt.CorreoElectronicoANotificar = datosUsuario.CorreoElectronicoANotificar; datosUsuarioExt.CorreoElectronicoPrincipal = datosUsuario.CorreoElectronicoPrincipal; datosUsuarioExt.Departamento = datosUsuario.Departamento; datosUsuarioExt.Descripcion = datosUsuario.Descripcion; datosUsuarioExt.DescripPuesto = datosUsuario.DescripPuesto; datosUsuarioExt.Estado = datosUsuario.Estado; datosUsuarioExt.extension = datosUsuario.extension; datosUsuarioExt.FechaCreacion = datosUsuario.FechaCreacion; datosUsuarioExt.FechaExpiracion = datosUsuario.FechaExpiracion; datosUsuarioExt.FechaNacimiento = datosUsuario.FechaNacimiento; datosUsuarioExt.IdDepartamento = datosUsuario.IdDepartamento; datosUsuarioExt.Identificacion = datosUsuario.Identificacion; datosUsuarioExt.IdTipoUsuario = datosUsuario.IdTipoUsuario; datosUsuarioExt.IdUsuario = datosUsuario.IdUsuario; datosUsuarioExt.NoCarnet = datosUsuario.NoCarnet; datosUsuarioExt.Nombre = datosUsuario.Nombre; datosUsuarioExt.OcupaCambioContrasena = datosUsuario.OcupaCambioContrasena; datosUsuarioExt.Oficina = datosUsuario.Oficina; datosUsuarioExt.TipoUsuario = datosUsuario.TipoUsuario; datosUsuarioExt.UsuarioCreacion = datosUsuario.UsuarioCreacion; datosUsuarioExt.UsuarioModificacion = datosUsuario.UsuarioModificacion; datosUsuarioExt.UsuarioVencido = datosUsuario.UsuarioVencido; datosUsuarioExt.NombreCompleto = datosUsuario.Apellido1 + " " + datosUsuario.Apellido2 + " " + datosUsuario.Nombre; datosUsuarioExt.Id = datosUsuario.IdUsuario; datosUsuarioExt.LoginUsuario = usuario; //genera el JW Token y le pone expiración por defecto de 1 hora (esto es renovable) datosUsuarioExt.JWToken = JwtManager.GenerarToken(usuario); datosUsuarioExt.ExpiracionToken = DateTime.UtcNow.AddHours(1); //ya validó al usuario, obtiene los permisos (claims) //aca es donde ocupo obtener los permisos, luego de saber que las credenciales son válidas var consultaPermisos = ServiciosSeguridad.ConsultarPermisosUsuario(0, datosUsuario.IdUsuario, 0, 0, idUsuarioLogueado, usuarioLogueado, Utilitarios.Clases.Utilitarios.GetIpAddress(), "SessionId"); var datosPermisos = consultaPermisos.ObjetoRespuesta; var datosCompletos = new { datosUsuario = datosUsuarioExt, datosPermisos = datosPermisos }; //validación correcta del usuario y pone los datos para set retornados los datos objResValidar.CodigoRespuesta = 0; objResValidar.MensajeRespuesta = ""; objResValidar.ObjetoRespuesta = new JavaScriptSerializer().Serialize(datosCompletos); res = Ok(objResValidar); } else { objResValidar.CodigoRespuesta = -1; objResValidar.MensajeRespuesta = "Credenciales inválidas"; } //fin poner datos... } else { //no viene el parametro usuario en el header res = Ok(-2); //SBP#33 - faltan credenciales pero genera credenciales incorrectas } } catch (Exception ex) { res = Ok(-1); //error genérico } } //else del if (NoSecTec) return(res); }
public ActionResult GetFileList(int pageIndex = 1, int pageSize = 10, string from = "", string filter = "", string fileType = "", DateTime?startTime = null, DateTime?endTime = null, Dictionary <string, string> sorts = null, bool delete = false) { FileClientService fileClientService = new FileClientService(fileServiceUrl, JwtManager.GetAuthorization(Request)); var filelist = fileClientService.GetFileList(pageIndex, pageSize, from, filter, fileType, startTime, endTime, sorts, delete); return(Content(JsonSerializerHelper.Serialize(filelist))); }
public async Task <IHttpActionResult> ObtenerDataCredito(ExperianViewModels experian) { try { var idUser = JwtManager.getIdUserSession(); var Usuario = await _ir.Find <Usuario>(idUser); experian.password = WebConfigurationManager.AppSettings["Experian_Password"].ToString(); experian.username = WebConfigurationManager.AppSettings["Experian_User"].ToString(); experian.grant_type = WebConfigurationManager.AppSettings["Experian_Gran_Type"].ToString(); experian.documentType = "1"; experian.document = Usuario.identificacion; var user = await _ir.GetFirst <Usuario>(z => z.identificacion == experian.document); if (user != null && !String.IsNullOrEmpty(user.responseDataExperian)) { // Fecha Auxiliar DateTime now = DateTime.Now; // Sumamos 1 mes a la fecha guardada DateTime date = user.fechaAccesoExperian.GetValueOrDefault().AddMonths(1); // Comparamos la fecha modificada, si es menor significa que ya pasó un mes y hay // que hacer la petición si no retorna lo que está almacenado if (date < now) { var fun = new FuncionesViewModels(); var token = fun.TokenDataExperian(experian); var respuesta = fun.ClienteDataExperian(experian, token); //object respuesta = null; if (respuesta != null) { var t = await _ir.GetFirst <Usuario>(z => z.identificacion == experian.document); if (t != null) { JavaScriptSerializer java = new JavaScriptSerializer(); t.responseDataExperian = Convert.ToString(respuesta); t.fechaAccesoExperian = DateTime.Now; await _ir.Update(t, t.idUsuario); } return(Ok(respuesta)); } else { return(Ok("Sin datos para esta identificación")); } } else { var data = JsonConvert.DeserializeObject(user.responseDataExperian); return(Ok(data)); } } else { var fun = new FuncionesViewModels(); var token = fun.TokenDataExperian(experian); var respuesta = fun.ClienteDataExperian(experian, token); //object respuesta = null; if (respuesta != null) { var t = await _ir.GetFirst <Usuario>(z => z.identificacion == experian.document); if (t != null) { JavaScriptSerializer java = new JavaScriptSerializer(); t.responseDataExperian = Convert.ToString(respuesta); t.fechaAccesoExperian = DateTime.Now; await _ir.Update(t, t.idUsuario); } return(Ok(respuesta)); } else { return(Ok("Sin datos para esta identificación")); } } } catch (Exception ex) { return(BadRequest(ex.Message)); } }
public ActionResult DownloadFile(string id, string filename) { FileClientService fileClientService = new FileClientService(fileServiceUrl, JwtManager.GetAuthorization(Request)); var fileItem = fileClientService.DownloadFile(id, filename); return(File(fileItem.FileStream, fileItem.ContentType)); }
public async System.Threading.Tasks.Task <JObject> PostAsync([FromBody] object value) { #region 变量声明以及初始化 JObject jObject = (JObject)value; //获取为Json对象 JObject result; //返回结果 ErrorRootobject error = new ErrorRootobject(); error.ReturnCode = "00001"; error.msg = "JSON format error"; string serial = JsonConvert.SerializeObject(error); //将实体类序列化为JSON字符串 result = (JObject)JsonConvert.DeserializeObject(serial); //将JSON字符串反序列化为JObject对象 string username = "******"; string password = "******"; #endregion #region 检查表单 try { username = jObject["username"].ToString(); password = jObject["password"].ToString(); } catch { error.ReturnCode = "00001"; error.msg = "JSON format error"; serial = JsonConvert.SerializeObject(error); //将实体类序列化为JSON字符串 result = (JObject)JsonConvert.DeserializeObject(serial); //将JSON字符串反序列化为JObject对象 return(result); } #endregion #region 用户名以及密码的判空 if (username == "" || password == "") { error.ReturnCode = "00009"; error.msg = "Username or password can not be null"; serial = JsonConvert.SerializeObject(error); //将实体类序列化为JSON字符串 result = (JObject)JsonConvert.DeserializeObject(serial); //将JSON字符串反序列化为JObject对象 return(result); } #endregion #region 用户名以及密码的危险字符检查 //排查危险字符 bool unameDanger = Regex.IsMatch(username, @"[-|;|,|\/|||||\}|\{|%|@|\*|!|\']"); bool pwdDanger = Regex.IsMatch(password, @"[-|;|,|\/|||||\}|\{|%|@|\*|!|\']"); if (unameDanger) { //失败后返回错误原因: error = new ErrorRootobject(); error.ReturnCode = "0002"; error.msg = "Username contains dangerous characters "; serial = JsonConvert.SerializeObject(error); //将实体类序列化 为JSON字符串 result = (JObject)JsonConvert.DeserializeObject(serial); //将JSON字符串反序列化为JObject对象 return(result); } if (pwdDanger) { //失败后返回错误原因: error = new ErrorRootobject(); error.ReturnCode = "0003"; error.msg = "Password contains dangerous characters "; serial = JsonConvert.SerializeObject(error); //将实体类序列化 为JSON字符串 result = (JObject)JsonConvert.DeserializeObject(serial); //将JSON字符串反序列化为JObject对象 return(result); } #endregion #region 检查用户名是否存在 //将安全的用户名和密码查询数据库 //首先查询用户名是否存在 var conn = anJiaContext.Database.GetDbConnection(); conn.Open(); var command = conn.CreateCommand(); string query = "SELECT Username " + "FROM Users " + "WHERE Username = '******'"; command.CommandText = query; DbDataReader unameReader = await command.ExecuteReaderAsync(); //用户名不存在 if (!unameReader.HasRows) { conn.Close(); //密码不匹配返回错误原因: error = new ErrorRootobject { ReturnCode = "0004", msg = "Username does not exist" }; serial = JsonConvert.SerializeObject(error); //将实体类序列化 为JSON字符串 result = (JObject)JsonConvert.DeserializeObject(serial); //将JSON字符串反序列化为JObject对象 unameReader.Dispose(); //释放资源 return(result); } else { conn.Close(); } #endregion #region 用户名与密码匹配验证 conn.Open(); query = "SELECT Username, Password " + "FROM Users " + "WHERE Username = '******'" + " AND password = '******'"; command.CommandText = query; DbDataReader reader = await command.ExecuteReaderAsync(); if (reader.HasRows) { conn.Close();//关闭连接 #region 单点登录逻辑 //检测是Redis中是否已经有关联 var redis = RedisHelper.GetRedisHelper(); if (redis.SignInCheck(username)) { RedisHelper.GetRedisHelper().DeleteKey(username); //删除原来的对应关系 } var accessToken = JwtManager.GetJwtManager().GenerateToken(username); //生成新Token redis.SetValue(username, accessToken); //在redis中建立用户名和Token的对应关系 #endregion LoginSuccessRootobject actoken = new LoginSuccessRootobject { AccessToken = accessToken//获取一个Token }; error = new ErrorRootobject { ReturnCode = "0010", msg = "Token failed to get" }; serial = JsonConvert.SerializeObject(actoken); //将实体类序列化为JSON字符串 result = (JObject)JsonConvert.DeserializeObject(serial); //将JSON字符串反序列化为JObject对象 } else { conn.Close(); //密码不匹配返回错误原因: error = new ErrorRootobject(); error.ReturnCode = "0005"; error.msg = "Incorrect username or password"; serial = JsonConvert.SerializeObject(error); //将实体类序列化 为JSON字符串 result = (JObject)JsonConvert.DeserializeObject(serial); //将JSON字符串反序列化为JObject对象 } reader.Dispose(); //释放资源 #endregion return(result); }
public ActionResult GetFromList() { FileClientService fileClientService = new FileClientService(fileServiceUrl, JwtManager.GetAuthorization(Request)); var froms = fileClientService.GetFromList(); return(Content(JsonSerializerHelper.Serialize(froms))); }
public async Task <ActionResult> FacebookPost([FromBody] FacebookDTO value) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } try { var appAccessTokenResponse = await Client.GetStringAsync($"https://graph.facebook.com/oauth/access_token?client_id={Facebook.AppId}&client_secret={Facebook.AppSecret}&grant_type=client_credentials"); var appAccessToken = JsonConvert.DeserializeObject <FacebookAppAccessToken>(appAccessTokenResponse); var userAccessTokenValidationResponse = await Client.GetStringAsync($"https://graph.facebook.com/debug_token?input_token={value.AccessToken}&access_token={appAccessToken.AccessToken}"); var userAccessTokenValidation = JsonConvert.DeserializeObject <FacebookUserAccessTokenValidation>(userAccessTokenValidationResponse); if (!userAccessTokenValidation.Data.IsValid) { return(BadRequest("Invalid facebook token!")); } var userInfoResponse = await Client.GetStringAsync($"https://graph.facebook.com/v3.2/me?fields=id,email,first_name,last_name,name,picture&access_token={value.AccessToken}"); var userInfo = JsonConvert.DeserializeObject <FacebookUserData>(userInfoResponse); var user = await userManager.FindByEmailAsync(userInfo.Email); if (user == null) { var userRole = await roleManager.FindByNameAsync("Student"); string picture = Convert.ToBase64String(await userService.GetImgBytesAsync(userInfo.Picture.Data.Url)); User newUser = new User { FirstName = userInfo.FirstName, LastName = userInfo.LastName, Email = userInfo.Email, UserName = userInfo.Email, Image = picture, Image_Name = userInfo.Name + "_Picture", Role = userRole, Role_Id = userRole.Id, EmailConfirmed = true }; var result = await userManager.CreateAsync(newUser, Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Substring(0, 8)); if (!result.Succeeded) { return(BadRequest()); } } var localUser = await userManager.FindByNameAsync(userInfo.Email); if (localUser == null) { return(BadRequest("Failed to create local user account.")); } var userDto = new UserIdentityDTO() { Email = localUser.Email, LastName = localUser.LastName, FirstName = localUser.FirstName, Id = localUser.Id, Role = localUser.Role.Name, EmailConfirmed = localUser.EmailConfirmed, Blocked = localUser.Blocked, Password = localUser.Password }; string jwt = JwtManager.GenerateToken(userDto); return(new JsonResult(jwt)); } catch (Exception e) { return(StatusCode(500)); } }
public SignalRHub(Database database, SignInManager <ApplicationUser> siginmanager, UserManager <ApplicationUser> userManager, JwtManager jwtManager) { this.database = database; this.siginmanager = siginmanager; this.userManager = userManager; this.jwtManager = jwtManager; }