Пример #1
0
        /// <summary>
        /// 重設密碼 - 根據email
        /// </summary>
        /// <param name="code">client所輸入的驗證碼</param>
        /// <param name="checkCode">系統所產生的驗證碼</param>
        /// <param name="email">client所輸入的驗證信箱</param>
        /// <returns></returns>
        public bool Do(string code, string checkCode, string email)
        {
            var memberService = new MemberService();
            var checkeMail    = _uow.MembersRepo.GetFirst(t => t.Email == email);

            //驗證該信箱是否註冊過
            if (checkeMail == null)
            {
                return(false);
            }
            //驗證碼是否輸入正確
            if (code.ToLower() != checkCode.ToLower())
            {
                return(false);
            }

            var captchaHelper     = new Utility.CaptchaHelper();
            var randomPwd         = captchaHelper.GenerateRandomText(10).ToLower();
            var encryptionService = new Utility.Encryption();
            //設定新密碼
            var newPassWord = encryptionService.StringToSHA256(string.Format("{0}{1}", randomPwd, checkeMail.Account));

            checkeMail.PassWord = newPassWord;
            _uow.SaveChanges();
            var mailService       = new MailService();
            var emailDomain       = ConfigurationManager.AppSettings["MailDomain"].ToString();
            var emailAdminAddress = ConfigurationManager.AppSettings["MailAdminAddress"].ToString();
            var emailSMTPPort     = Convert.ToInt32(ConfigurationManager.AppSettings["MailSMTPPort"].ToString());
            //收信者
            var recipient = new List <string>()
            {
                email
            };
            var msg      = string.Format("{0}您好!!您的密碼是{1}", checkeMail.Name, randomPwd);
            var sendMail = mailService.SendMail(emailDomain, emailSMTPPort, emailAdminAddress, recipient, msg, "Locus重設密碼", null).Result;

            return(sendMail);
        }
Пример #2
0
        /// <summary>
        /// 取得APP的GetAllMyCourse的資訊
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public IEnumerable <Infrastructure.ViewModel.CourseManage.GetAllMyCourseResponse> APPGetAllMyCourse(string token)
        {
            var memberService = new MemberService();
            var checkToken    = memberService.TokenToMember(token).Result;

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

            var sectionService = new SectionService();
            var sectionData    = sectionService.GetOrgNowSeme(checkToken.OrgId);


            var learningCircleList = GetLearningCircleListByToken(token, null, null);

            if (learningCircleList == null || learningCircleList.Count() <= 0)
            {
                return(new List <Infrastructure.ViewModel.CourseManage.GetAllMyCourseResponse>());
            }
            var response    = new List <Infrastructure.ViewModel.CourseManage.GetAllMyCourseResponse>();
            var sectionYear = learningCircleList.Where(t => t.StartDate.HasValue).GroupBy(t => t.StartDate.Value.Year);

            //上過多少學年度
            foreach (var year in sectionYear)
            {
                var data       = new Infrastructure.ViewModel.CourseManage.GetAllMyCourseResponse();
                var courseData = new List <Infrastructure.ViewModel.CourseManage.DataCourseDataModel>();
                data.Year     = year.Key;
                data.YearSeme = year.Key.ToString();
                if (year.Key == sectionData.Year)
                {
                    data.IsNowSeme = true;
                }
                //查詢課程
                foreach (var learningcircle in learningCircleList.Where(t => t.StartDate.HasValue && ((t.StartDate >= sectionData.StartDate && t.StartDate <= sectionData.EndDate) || (t.EndDate >= sectionData.StartDate && t.EndDate <= sectionData.EndDate))))
                {
                    var learningCircleData = new Infrastructure.ViewModel.CourseManage.DataCourseDataModel();

                    learningCircleData.ClassId          = learningcircle.LearningOuterKey.ToLower();
                    learningCircleData.ClassName        = learningcircle.Name;
                    learningCircleData.ClassSubjectName = learningcircle.Name;
                    //查詢課程老師們
                    var teachers        = memberService.GetTeacherList(learningcircle.LearningOuterKey);
                    var teacherListData = new List <Infrastructure.ViewModel.MemberManage.TeacherPhotoInfo>();
                    var teacherNames    = string.Empty;
                    //設定上課老師們資料
                    foreach (var teacher in teachers)
                    {
                        var teacherData = new Infrastructure.ViewModel.MemberManage.TeacherPhotoInfo();
                        teacherData.Email   = teacher.Email;
                        teacherData.ManName = teacher.Name;
                        teacherData.Url     = teacher.Photo;
                        teacherListData.Add(teacherData);
                        teacherNames += teacher.Name + ",";
                    }
                    teacherNames = teacherNames != string.Empty ? teacherNames.Substring(0, teacherNames.Length - 1) : teacherNames;
                    learningCircleData.TeacherPhoto = teacherListData.ToArray();
                    learningCircleData.ClassTeacher = teacherNames;
                    learningCircleData.StartDate    = learningcircle.StartDate.HasValue ? learningcircle.StartDate.Value.ToLocalTime() : DateTime.MinValue;
                    learningCircleData.EndDate      = learningcircle.EndDate.HasValue ? learningcircle.EndDate.Value.ToLocalTime() : DateTime.MinValue;
                    var memberCount = memberService.GetLearningCircleMembers(learningcircle.LearningOuterKey).Count();
                    learningCircleData.MemberCount = memberCount;
                    var weekTableService = new WeekTableService();
                    var weekDatas        = weekTableService.GetAllMyCourseWeekTableData(learningcircle.Id);
                    if (weekDatas != null)
                    {
                        learningCircleData.WeekTable = weekDatas.ToList();
                    }
                    courseData.Add(learningCircleData);
                }
                data.Course = courseData.ToArray();
                response.Add(data);
            }
            return(response);
        }
Пример #3
0
        /// <summary>
        /// 取得APP的GetCourseDetail的資訊
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public Infrastructure.ViewModel.CourseManage.GetCourseDetailResponse APPGetCourseDetail(string token, string circleKey)
        {
            var response      = new Infrastructure.ViewModel.CourseManage.GetCourseDetailResponse();
            var memberService = new MemberService();
            var tokenService  = new TokenService();
            var checkToken    = tokenService.GetTokenInfo(token);

            if (checkToken == null)
            {
                return(response);
            }

            var members = memberService.GetLearningCircleMembers(circleKey);

            if (members == null)
            {
                return(response);
            }

            response.MemberCount    = members.Count();
            response.Edit           = false;
            response.EditImpression = false;
            response.CollInfo       = null;

            var learningCircleInfo = GetDetailByOuterKey(circleKey);

            if (learningCircleInfo == null)
            {
                return(response);
            }

            //處理老師名單
            var teachers = memberService.GetTeacherList(circleKey);

            if (teachers.FirstOrDefault() != null)
            {
                var teachersName = teachers.Select(t => t.Name).ToList();
                foreach (var teacher in teachersName)
                {
                    response.ClassTeachers += teacher + "、";
                }
                response.ClassTeachers = response.ClassTeachers.Substring(0, response.ClassTeachers.Length - 1);
            }
            if (learningCircleInfo.StartDate.HasValue && learningCircleInfo.EndDate.HasValue)
            {
                response.ClassPeriod = string.Format("{0} ~ {1}", learningCircleInfo.StartDate.Value.ToLocalTime().ToString("yyyy/MM/dd"), learningCircleInfo.EndDate.Value.ToLocalTime().ToString("yyyy/MM/dd"));
                response.StartDate   = learningCircleInfo.StartDate.Value.ToLocalTime();
                response.EndDate     = learningCircleInfo.EndDate.Value.ToLocalTime();
            }

            var weekTableService    = new WeekTableService();
            var ClassWeekTableDatas = weekTableService.GetByCirclekey(circleKey);

            response.WeekTable = new List <Infrastructure.ViewModel.CourseManage.GetAllMyCourseWeekTable>();
            if (ClassWeekTableDatas.WeekTable.FirstOrDefault() != null)
            {
                foreach (var weekTableData in ClassWeekTableDatas.WeekTable)
                {
                    var data = new Infrastructure.ViewModel.CourseManage.GetAllMyCourseWeekTable()
                    {
                        Week        = weekTableData.Week,
                        Place       = weekTableData.Place,
                        StartPeriod = weekTableData.StartPeriod.Value,
                        EndPeriod   = weekTableData.EndPeriod.Value,
                        StartTime   = string.Format("{0:HH}:{0:mm}", weekTableData.StartTime.ToLocalTime()),
                        EndTime     = string.Format("{0:HH}:{0:mm}", weekTableData.EndTime.ToLocalTime())
                    };
                    response.WeekTable.Add(data);
                }
            }

            response.ClassSubjectName = learningCircleInfo.Name;
            response.ClassId          = learningCircleInfo.LearningOuterKey;
            response.Introduction     = learningCircleInfo.Description;
            response.ClassName        = learningCircleInfo.Name;
            response.ClassDomainId    = null;
            response.ClassDomainName  = null;
            response.Note             = learningCircleInfo.ReMark;
            response.ClassTarget      = learningCircleInfo.Objective;
            return(response);
        }
Пример #4
0
        /// <summary>
        /// 儲存個人照片檔案
        /// </summary>
        /// <param name="token"></param>
        /// <param name="account"></param>
        /// <param name="photo"></param>
        /// <returns></returns>
        public Infrastructure.ViewModel.MemberManage.MemberPhotoResponse SaveMemberPhotoFile(string token, string account, string photo)
        {
            var db            = _uow.DbContext;
            var memberService = new MemberService();
            var tokenService  = new TokenService();
            var checkToken    = tokenService.GetTokenInfo(token).Result;

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

            var memberData = db.Members.Find(checkToken.MemberId);

            //    var memberInfo = memberService.UserIdToAccount(checkToken.MemberId);
            if (memberData == null)
            {
                return(null);
            }
            int?fileImageWidth  = null;
            int?fileImageHeight = null;
            var fileGuidName    = Guid.NewGuid();
            var resourcePath    = Path.Combine(drivePath, fileGuidName.ToString("N"));

            var photoData   = Convert.FromBase64String(photo);
            var photoStream = new System.IO.MemoryStream(photoData);
            var photoBitmap = new Bitmap(new MemoryStream(photoData));

            //原始圖片檔
            SetPhotoFileInfo(photoBitmap, resourcePath);

            var imgResizePath = Path.Combine(drivePath, string.Format("{0}_w{1}_h{2}", fileGuidName.ToString("N"), maxImgWidth, maxImgHeight));

            //縮圖檔
            SetPhotoFileResizeInfo(photoBitmap, resourcePath, maxImgWidth, maxImgHeight, imgResizePath);
            var image = System.Drawing.Image.FromStream(photoStream);

            //實體圖片寬高
            fileImageWidth  = image.Width;
            fileImageHeight = image.Width;
            var imgContentType = "image/png";
            var fileServer     = WebConfigurationManager.AppSettings["loginServer"];
            var fileEntity     = new Infrastructure.Entity.FileStorage()
            {
                Name            = memberData.Name + "照片",
                FileGuid        = fileGuidName,
                FileSize        = photoData.Length, //Byte
                FileContentType = imgContentType,
                Creator         = memberData.Id,
                CreateUtcDate   = DateTime.UtcNow,
                FileUrl         = string.Format("{0}api/file/{1}", fileServer, fileGuidName.ToString("N")),

                FileImageHeight = fileImageHeight,
                FileImageWidth  = fileImageWidth
            };

            // Db File
            var fileImgData = Create(fileEntity);

            memberData.Photo      = fileImgData.FileImageUrl;
            memberData.Updated    = TimeData.Create(DateTime.UtcNow);
            memberData.UpdateUser = memberData.Id;
            db.SaveChanges();

            var response = new Infrastructure.ViewModel.MemberManage.MemberPhotoResponse();

            response.AcpdId = account;
            response.Photo  = fileImgData.FileImageUrl;
            return(response);
        }
Пример #5
0
        /// <summary>
        /// 確認課程管理權限
        /// </summary>
        /// <param name="token"></param>
        /// <param name="circleKey"></param>
        /// <returns></returns>
        public CourseManageAuthResponse CheckCourseManageAuth(string token, string circleKey)
        {
            var memberService = new MemberService();
            var memberInfo    = memberService.TokenToMember(token).Result;

            if (memberInfo == null)
            {
                return(null);
            }
            var learningCircleService = new LearningCircleService();
            var learningInfo          = learningCircleService.GetDetailByOuterKey(circleKey.ToLower());

            if (learningInfo == null)
            {
                return(null);
            }
            var responseData = new CourseManageAuthResponse()
            {
                CircleAdminSetting    = new CircleAdminSettingAuth(),
                CircleInfoSetting     = new CircleInfoSettingAuth(),
                CircleMemberSetting   = new CircleMemberSettingAuth(),
                CircleRoleSetting     = new CircleRoleSettingAuth(),
                CircleScheduleSetting = new CircleScheduleSettingAuth(),
                CircleTimelistSetting = new CircleTimelistSettingAuth()
            };

            //課程管理者
            var isCourseManage = CheckCourseAdmin(memberInfo.Id, circleKey);
            //分類系所管理者
            var isDepartmentAdmin   = CheckDepartmentAdmin(memberInfo.Id, memberInfo.OrgId);
            var learningRoleService = new LearningRoleService();
            //查看查詢者在課程裡的角色
            var myRole = learningRoleService.GetMyRole(token, circleKey);

            //如果是匯入的課程
            if (learningInfo.ExternalRid != null)
            {
                responseData = SetCourseManageAuth(
                    //判斷是否為課程管理者
                    (isCourseManage || ((learningInfo.OrgId.Value == memberInfo.OrgId && memberInfo.IsOrgAdmin) || isDepartmentAdmin)),
                    myRole.Level == 1, //判斷是否為老師身分
                    myRole.Level == 2, //判斷是否為助教身分
                    true);             //是匯入所以是true
                return(responseData);
            }
            //一般課程管理者
            if (isCourseManage || ((learningInfo.OrgId.Value == memberInfo.OrgId && memberInfo.IsOrgAdmin) || isDepartmentAdmin))
            {
                responseData = SetCourseManageAuth(true);
                return(responseData);
            }
            if (myRole == null)
            {
                return(null);
            }
            switch (myRole.Level)
            {
            //如果是老師
            case 1:
                responseData = SetCourseManageAuth(false, true);
                return(responseData);

            //如果是助教
            case 2:
                responseData = SetCourseManageAuth(false, false, true);
                return(responseData);

            default:
                return(null);
            }
        }
Пример #6
0
        public List <Infrastructure.ViewModel.School.GetCampusEventGetResponse> GetList
            (Infrastructure.ViewModel.Base.BackendBaseRequest requestData)
        {
            var db            = _uow.DbContext;
            var responseData  = new List <Infrastructure.ViewModel.School.GetCampusEventGetResponse>();
            var memberService = new MemberService();
            var memberInfo    = memberService.TokenToMember(requestData.Token).Result;

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

            var sectionService = new SectionService();
            var sectionData    = sectionService.GetOrgNowSeme(memberInfo.OrgId);

            var dbDatas = (from c in db.Calendar
                           join m in db.Members on c.Creator equals m.Id
                           join f in db.FileStorage on c.FileId equals f.Id into ps
                           from o in ps.DefaultIfEmpty()
                           join csg in db.CalendarSemester on c.Id equals csg.CalendarId into csgg
                           from csggt in csgg.DefaultIfEmpty()
                           join cor in db.CalendarOrganizationRole on c.Id equals cor.CalendarId into corg
                           from corgt in corg.DefaultIfEmpty()
                           join cd in db.CalendarDept on c.Id equals cd.CalendarId into cdg
                           from cdgt in cdg.DefaultIfEmpty()
                           where c.OrgId == memberInfo.OrgId && (c.StartDate >= sectionData.StartDate && c.StartDate <= sectionData.EndDate)
                           select new Infrastructure.ViewModel.School.GetCampusEventGetResponse
            {
                Id = c.Id,
                BoarderID = c.Code,
                CreateDate = c.CreateDate.Value,
                CreateMan = m.Account,
                EndDate = c.EndDate,
                IsBigEvent = c.IsBigEvent,
                StartDate = c.StartDate,
                TitleC = c.Title,
                UpdateDate = c.UpdateDate,
                Updater = c.Updater,
                Url = o.FileUrl,
                DeptId = cdgt.DeptId,
                OrganizationRoleId = corgt.OrganizationRoleId,
                SemesterGradeId = csggt.SemesterId
            }).ToList();

            if (dbDatas.FirstOrDefault() == null)
            {
                return(null);
            }

            var memberDept = memberInfo.DeptId.HasValue ? db.Depts.FirstOrDefault(t => t.Id == memberInfo.DeptId.Value) : new Infrastructure.Entity.Dept();
            var memberSemesterGradeInfo = memberInfo.SemesterGradeId.HasValue ? db.SemesterGrade.FirstOrDefault(t => t.Id == memberInfo.SemesterGradeId.Value) : new Infrastructure.Entity.SemesterGrade();
            var memberOrgRoleInfo       = memberInfo.OrganizationRoleId.HasValue ? db.OrganizationRole.FirstOrDefault(t => t.Id == memberInfo.OrganizationRoleId) : new Infrastructure.Entity.OrganizationRole();

            responseData.AddRange(dbDatas);
            //整理資料
            foreach (var dbData in dbDatas)
            {
                if (dbData.Updater.HasValue)
                {
                    dbData.UpdateDate = dbData.UpdateDate.HasValue ? dbData.UpdateDate.Value.ToLocalTime() : dbData.UpdateDate;
                    dbData.UpDateMan  = (dbData.UpDateMan != null && dbData.UpDateMan != string.Empty) ? dbData.UpDateMan : null;
                }
                dbData.CreateDate = dbData.CreateDate.Value.ToLocalTime();
                dbData.StartDate  = dbData.StartDate.ToLocalTime();
                dbData.EndDate    = dbData.EndDate.ToLocalTime();
                dbData.PeriodWeek = GetPeriodWeek(dbData.StartDate, dbData.EndDate, memberInfo.OrgId);
                //假設事件有限制學制顯示
                if (dbData.SemesterGradeId.HasValue)
                {
                    //不是該學制的看不到
                    if (memberSemesterGradeInfo.Id <= 0 || memberSemesterGradeInfo.Id != dbData.SemesterGradeId.Value)
                    {
                        responseData.Remove(dbData);
                    }
                }
                //事件有限制角色顯示
                if (dbData.OrganizationRoleId.HasValue)
                {
                    //不是該角色看不到
                    if (memberOrgRoleInfo.Id <= 0 || memberOrgRoleInfo.Id != dbData.OrganizationRoleId.Value)
                    {
                        responseData.Remove(dbData);
                    }
                }
                //事件有限制學院分類顯示
                if (dbData.DeptId.HasValue)
                {
                    //不屬於該學院分類看不到
                    if (memberDept.Id <= 0 || memberDept.Id != dbData.OrganizationRoleId.Value)
                    {
                        responseData.Remove(dbData);
                    }
                }
            }

            return(responseData);
        }
Пример #7
0
        /// <summary>
        /// 組織登入API
        /// </summary>
        /// <param name="account"></param>
        /// <param name="pwd"></param>
        /// <param name="deviceId"></param>
        /// <param name="orgId"></param>
        /// <returns></returns>
        public async Task <bool> OrganizationLoginCheck(string loginUrl, LoginRequest data, int orgId)
        {
            var db              = _uow.DbContext;
            var response        = false;
            var loginColumnKeys = db.OrganizationLoginColumn.Where(t => t.OrgId == orgId);
            var checkColumn     = loginColumnKeys.FirstOrDefault();

            if (checkColumn == null)
            {
                return(response);
            }

            var contentJson       = string.Empty;
            var tokenInfo         = new Infrastructure.ViewModel.Base.BackendBaseRequest();
            var schoolLoginKey    = ConfigurationManager.AppSettings["iCanLoginKey"].ToString();
            var appLoginKey       = ConfigurationManager.AppSettings["AppLoginKey"].ToString();
            var encryptionService = new Encryption();
            var accounts          = data.Account.Split('@');
            var account           = accounts[0];
            var simulateAccount   = accounts.Count() > 1 ? accounts[1] : account;

            //有模擬登入者,需要驗證模擬登入者是否為系統管理者
            if (accounts.Count() > 1)
            {
                var checkSimulatorAuth = db.Members.FirstOrDefault(t => t.Account == account).RoleName == "1";
                if (checkSimulatorAuth == false)
                {
                    return(false);
                }
            }


            using (var httpClient = new HttpClient())
            {
                var password = encryptionService.EncryptString(encryptionService.DecryptString(data.Password, appLoginKey), schoolLoginKey);
                if (checkColumn.Method.ToLower() == "post")
                {
                    var jsonData = "{";
                    foreach (var column in loginColumnKeys)
                    {
                        switch (column.Type.ToLower())
                        {
                        case "account":
                            jsonData = string.Format("{0}\"{1}\":\"{2}\",", jsonData, column.ColumnKey, account);
                            break;

                        case "pwd":
                            jsonData = string.Format("{0}\"{1}\":\"{2}\",", jsonData, column.ColumnKey, password);
                            break;

                        case "devicekey":
                            jsonData = string.Format("{0}\"{1}\":\"{2}\",", jsonData, column.ColumnKey, data.PhoneID);
                            break;

                        case "simulate":
                            jsonData = string.Format("{0}\"{1}\":\"{2}\",", jsonData, column.ColumnKey, simulateAccount);
                            break;

                        default:
                            break;
                        }
                    }
                    jsonData = jsonData.Substring(0, jsonData.Length - 1);
                    httpClient.BaseAddress = new Uri(loginUrl);
                    jsonData += "}";
                    var request = new HttpRequestMessage(HttpMethod.Post, loginUrl);
                    request.Content = new StringContent(jsonData, Encoding.UTF8, "application/json");
                    var responseContent = httpClient.SendAsync(request);
                    if (responseContent.Result.IsSuccessStatusCode)
                    {
                        var responseString = responseContent.Result.Content.ReadAsStringAsync().Result;
                        tokenInfo = JsonConvert.DeserializeObject <Infrastructure.ViewModel.Base.BackendBaseRequest>(responseString);
                    }
                }
                else if (checkColumn.Method.ToLower() == "get")
                {
                    loginUrl += "?";
                    foreach (var column in loginColumnKeys)
                    {
                        switch (column.Type.ToLower())
                        {
                        case "account":
                            loginUrl = string.Format("{0}{1}={2}&", loginUrl, column.ColumnKey, account);
                            break;

                        case "pwd":
                            loginUrl = string.Format("{0}{1}={2}&", loginUrl, column.ColumnKey, password);
                            break;

                        case "devicekey":
                            loginUrl = string.Format("{0}{1}={2}&", loginUrl, column.ColumnKey, data.PhoneID);
                            break;

                        case "simulate":
                            loginUrl = string.Format("{0}{1}={2}&", loginUrl, column.ColumnKey, simulateAccount);
                            break;

                        default:
                            break;
                        }
                    }
                    loginUrl = loginUrl.Substring(0, loginUrl.Length - 1);
                    var responseContent = await httpClient.GetAsync(loginUrl);

                    var responseString = responseContent.Content.ReadAsStringAsync().Result;
                    tokenInfo = JsonConvert.DeserializeObject <BackendBaseRequest>(responseString);
                }

                response = tokenInfo.Success;
                if (tokenInfo.Success)
                {
                    var tokenService    = new TokenService();
                    var memberService   = new MemberService();
                    var orgToken        = tokenInfo.Token != null && tokenInfo.Token != string.Empty ? tokenInfo.Token : Guid.NewGuid().ToString().ToLower();
                    var loginMemberInfo = data.OrgId.HasValue ?
                                          db.Members.FirstOrDefault(t => t.OrgId == data.OrgId.Value && t.Account == simulateAccount) :
                                          db.Members.FirstOrDefault(t => t.Account == simulateAccount);
                    var loginLogResponse = tokenService.InsertUserTokenByOrganization(data.RequestSystem, data.PhoneID, loginMemberInfo, data.PushToken, orgToken, loginMemberInfo.Id);
                }
            }
            return(response);
        }
Пример #8
0
        /// <summary>
        /// 取得角色列表 - 根據circleKey[新結構]
        /// </summary>
        /// <param name="circleKey"></param>
        /// <returns></returns>
        public IEnumerable <LearningRoleGetResponse> GetLearningRolesByCircleKey(string circleKey, string token)
        {
            var db = _uow.DbContext;
            var learningCircleService = new LearningCircleService();
            var learningCircleInfo    = learningCircleService.GetDetailByOuterKey(circleKey);

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

            var memberService = new MemberService();
            var memberInfo    = memberService.TokenToMember(token).Result;

            if (memberInfo == null)
            {
                return(null);
            }
            var checkTokenLevel = (from lr in db.LearningRole
                                   join cmr in db.CircleMemberRoleplay on lr.Id equals cmr.RoleId
                                   where cmr.CircleId == learningCircleInfo.Id && cmr.MemberId == memberInfo.Id
                                   select lr).FirstOrDefault();

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

            var responseData = (from lr in db.LearningRole
                                join lc in db.LearningCircle on lr.LearningId equals lc.Id
                                where lc.LearningOuterKey == circleKey && lr.Enable == true
                                select new LearningRoleGetResponse
            {
                Level = lr.Level,
                Name = lr.Name,
                RoleCode = lr.Ican5Memo,
                Id = lr.Id,
                IsFixed = lr.IsFixed,
                ExternalRid = lr.ExternalRid
            }).ToList();

            if (responseData.FirstOrDefault() == null)
            {
                return(null);
            }
            var authService       = new AuthService();
            var isDepartmentAdmin = authService.CheckDepartmentAdmin(memberInfo.Id, memberInfo.OrgId);

            foreach (var data in responseData)
            {
                if (data.ExternalRid.HasValue)
                {
                    data.IsEdit = false;
                    continue;
                }
                if ((isDepartmentAdmin == true || memberInfo.IsOrgAdmin == true))
                {
                    data.IsEdit = true;
                    continue;
                }
                if (checkTokenLevel.Level.Value < data.Level.Value)
                {
                    data.IsEdit = true;
                }
                else
                {
                    data.IsEdit = false;
                }
            }
            return(responseData);
        }
Пример #9
0
        /// <summary>
        /// 註冊帳號
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public UserPostResponse RegisterMember(RegisterRequest data, FileViewModel photo)
        {
            var memberService = new MemberService();
            var creatorInfo   = memberService.TokenToMember(data.Token).Result;

            if (creatorInfo == null)
            {
                return(null);
            }
            var encryptionService = new Encryption();

            var hostUrl = System.Configuration.ConfigurationManager.AppSettings["loginServer"].ToString();


            if (data.OrgCode == null || data.OrgCode == string.Empty)
            {
                data.OrgCode = "amateur";
            }

            var checkRegisted = GetMemberByAccountSchool(data.Account, data.OrgCode);

            //該帳號已經註冊過了
            if (checkRegisted != null)
            {
                return(null);
            }
            var db = _uow.DbContext;
            var organizationInfo = db.Organizations.FirstOrDefault(t => t.OrgCode == data.OrgCode);

            try
            {
                var newMember = new Member()
                {
                    Account     = data.Account,
                    Created     = TimeData.Create(DateTime.UtcNow),
                    Deleted     = TimeData.Create(null),
                    Updated     = TimeData.Create(null),
                    Name        = data.Name,
                    Email       = data.Email,
                    Enable      = true,
                    IsShowEmail = false,
                    Visibility  = true,
                    IsOrgAdmin  = Convert.ToInt32(data.RoleId) == 1 ? true : false,
                    OrgId       = organizationInfo.Id,
                    PassWord    = encryptionService.StringToSHA256(string.Format("{0}{1}", encryptionService.DecryptString(data.Pwd, appKey), data.Account)),
                    Photo       = string.Format("{0}{1}", hostUrl, "images/img-user.png"),
                    RoleName    = data.RoleId.ToString(),
                    Verified    = true,
                    CreateUser  = creatorInfo.Id,
                    ExternalRid = 0
                };
                db.Members.Add(newMember);
                //為了取得memberId
                db.SaveChanges();

                //上傳大頭照
                if (photo != null && photo.ContentLength > 0)
                {
                    var fileService  = new FileService();
                    var maxImgWidth  = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["maxImgWidth"].ToString());
                    var maxImgHeight = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["maxImgHeight"].ToString());
                    var drivePath    = System.Configuration.ConfigurationManager.AppSettings["DrivePath"].ToString();
                    var fileInfo     = fileService.UploadFile(newMember.Id, photo.FileName, photo.ContentType, photo.ContentLength, maxImgHeight, maxImgWidth);
                    var path         = Path.Combine(drivePath, fileInfo.FileGuid.ToString("N"));
                    var stream       = photo.InputStream;
                    /*stream轉bytes*/
                    var br = new BinaryReader(stream);
                    br.BaseStream.Seek(0, SeekOrigin.Begin);
                    var bytesInStream = br.ReadBytes((int)br.BaseStream.Length);
                    //實際檔案處理
                    fileService.FileProxy(photo.ContentLength, path, stream, bytesInStream);
                    newMember.Photo = fileInfo.FileImageUrl;
                    //最終儲存
                    db.SaveChanges();
                }
                var responseData = new UserPostResponse()
                {
                    CreateAccount = creatorInfo.Account,
                    CreateTime    = newMember.Created.Local.Value,
                    Enable        = newMember.Enable,
                    ExternalRid   = newMember.ExternalRid,
                    IsShowMail    = newMember.IsShowEmail,
                    Photo         = newMember.Photo,
                    Verified      = newMember.Verified
                };
                return(responseData);
            }
            catch (Exception ex)
            {
                return(null);

                throw ex;
            }
        }