Example #1
0
        public async Task <IActionResult> AddAccountAdmin(AdminRequest model)
        {
            var appUser = await _userManager.FindByNameAsync(model.Code);

            if (appUser != null)
            {
                return(new BadRequestObjectResult(new { type = 2, message = "Employee code already exists" }));
            }

            appUser = await _userManager.FindByEmailAsync(model.Email);

            if (appUser != null)
            {
                return(new BadRequestObjectResult(new { type = 1, message = "Email already exists" }));
            }

            var registerUser = new AppUser
            {
                Email    = model.Email,
                UserName = model.Code,
                RealName = model.RealName,
                DOB      = Convert.ToDateTime(model.Dob),
                Avatar   = "default.png"
            };

            var result = await _userManager.CreateAsync(registerUser, "123@123a");

            if (!result.Succeeded)
            {
                var internalErr = new ObjectResult(new { type = 2, error = result.Errors.ToList()[0].Description })
                {
                    StatusCode = 500
                };
                return(internalErr);
            }

            //Confirm email
            var urlHelper = _urlHelperFactory.GetUrlHelper(_actionContextAccessor.ActionContext);
            var token     = await _userManager.GenerateEmailConfirmationTokenAsync(registerUser);

            var confirmationLink = urlHelper.Action("ConfirmEmail", "Users", new { token, email = registerUser.Email }, "https");
            var content          = String.Format(EmailTemplate.HTML_CONTENT, model.Email, model.Code, "123@123a", confirmationLink);

            var message = new Message(new string[] { registerUser.Email }, "Your Account On DYSTANCE", content, null);
            await _emailSender.SendEmailAsync(message);


            await _userManager.AddToRoleAsync(registerUser, model.Role);


            return(new OkObjectResult(new AdminInfoResponse
            {
                Id = registerUser.Id,
                Code = registerUser.UserName,
                Email = registerUser.Email,
                RealName = registerUser.RealName,
                Dob = registerUser.DOB.ToString("yyyy-MM-dd"),
                Role = model.Role,
            }));
        }
Example #2
0
        public async Task <ActionResult> StoreSubjectQuestions(AdminRequest model)
        {
            ValidateRequest(model, _adminSettings);
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            //獲取所有歷屆試題Id
            var recruitQuestionIds = _questionsService.FetchAllRecruitQuestionIds();

            //專業科目(1):臺灣自然及人文地理
            var firstRootSubject = _subjectsService.GetById(_rootSubjectSettings.FirstId);

            await SaveSubjectQuestionsAsync(firstRootSubject, recruitQuestionIds);


            //專業科目(2):郵政法規大意及交通安全常識
            var secondRootSubject = _subjectsService.GetById(_rootSubjectSettings.SecondId);

            await SaveSubjectQuestionsAsync(secondRootSubject, recruitQuestionIds);


            return(Ok());
        }
Example #3
0
 protected void ValidateRequest(AdminRequest model, AdminSettings adminSettings)
 {
     if (model.Key != adminSettings.Key)
     {
         ModelState.AddModelError("key", "認證錯誤");
     }
 }
        public async Task <ActionResult> Admin(AdminRequest model)
        {
            ValidateRequest(model, _adminSettings);
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            //同步更新解析中的參考(因Note TermId可能變動)
            var resolves = await _resolvesService.FetchAsync();

            resolves = resolves.Where(x => !String.IsNullOrEmpty(x.Source)).ToList();

            var viewList = resolves.MapViewModelList(_mapper, new List <UploadFile>());

            foreach (var view in viewList)
            {
                foreach (var item in view.Sources)
                {
                    item.MapContent(_notesService, _termsService);
                }

                var entity = resolves.Where(x => x.Id == view.Id).FirstOrDefault();
                entity.Source = view.Sources.HasItems() ? JsonConvert.SerializeObject(view.Sources) : "";

                await _resolvesService.UpdateAsync(entity);
            }

            return(Ok());
        }
Example #5
0
        public ActionResult Backup([FromBody] AdminRequest model)
        {
            ValidateRequest(model, _adminSettings);
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var    connectionString = _context.Database.GetDbConnection().ConnectionString;
            string dbName           = GetDbName(connectionString);

            var folderPath = BackupFolder(_adminSettings);
            var fileName   = Path.Combine(folderPath, $"{dbName}_{DateTime.Now.ToString("yyyyMMddHHmmss")}.bak");

            string cmdText = $"BACKUP DATABASE [{dbName}] TO DISK = '{fileName}'";

            using (var conn = new SqlConnection(connectionString))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand(cmdText, conn))
                {
                    int result = cmd.ExecuteNonQuery();
                }
                conn.Close();
            }

            return(Ok());
        }
 public AdminResponse AdminRegistration(AdminRequest adminRequest)
 {
     if (adminRequest != null)
     {
         return(this.adminRepository.AdminRegistration(adminRequest));
     }
     return(null);
 }
Example #7
0
        public async Task <IActionResult> Post([FromBody] AdminRequest request)
        {
            await _ethereumClient.WaitForConfirmationAsync(request.TransactionHash);

            await _adminService.AddAsync(request.Address);

            return(NoContent());
        }
Example #8
0
        public ActionResult DeleteConfirmed(int id)
        {
            AdminRequest adminRequest = db.AdminRequests.Find(id);

            db.AdminRequests.Remove(adminRequest);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Example #9
0
        public async Task <ActionResult> Test([FromBody] AdminRequest model)
        {
            if (model.Key != _adminSettings.Key)
            {
                ModelState.AddModelError("key", "認證錯誤");
            }
            if (string.IsNullOrEmpty(model.Cmd))
            {
                ModelState.AddModelError("cmd", "指令錯誤");
            }
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }


            if (model.Cmd.EqualTo("remove-bill"))
            {
                var billView = JsonConvert.DeserializeObject <BillViewModel>(model.Data);
                _testsService.RemoveBill(billView.Id);

                return(Ok());
            }
            else if (model.Cmd.EqualTo("remove-subsrcibes"))
            {
                await _testsService.RemoveSubsrcibesFromUserAsync();

                await _testsService.RemoveBillsFromUserAsync();

                return(Ok());
            }
            else if (model.Cmd.EqualTo("fake-pay"))
            {
                var tradeResultModel = JsonConvert.DeserializeObject <TradeResultModel>(model.Data);

                var subscribe = await _subscribesService.StorePayAsync(tradeResultModel);

                if (subscribe != null)
                {
                    //付款訂閱完成
                    BackgroundJob.Enqueue(() => NotifyUserAsync(subscribe.UserId));
                }

                return(Ok("1|OK"));
            }
            else if (model.Cmd.EqualTo("login"))
            {
                var responseView = await _testsService.LoginAsync(RemoteIpAddress);

                return(Ok(responseView));
            }
            else
            {
                ModelState.AddModelError("cmd", "指令錯誤");
                return(BadRequest(ModelState));
            }
        }
Example #10
0
        public bool AdminDetails(AdminRequest request)
        {
            var name = _db.Admins.Where(a => a.AdminName == request.AdminName && a.AdminPassword == request.Password).FirstOrDefault();

            if (name != null)
            {
                return(true);
            }
            return(false);
        }
 public IActionResult AdminDetails(AdminRequest data)
 {
     var result = repository.AdminDetails(data);
     {
         if (result)
         {
             return(Ok(new { message = "Successfully LoggedIn" }));
         }
         return(Unauthorized("Authorization failed"));
     }
 }
Example #12
0
        public ActionResult Migrate([FromBody] AdminRequest model)
        {
            ValidateRequest(model, _adminSettings);
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            _context.Database.Migrate();

            return(Ok());
        }
Example #13
0
 public ActionResult Edit([Bind(Include = "Id,ContactEmail,TitleName,FirstName,LastName,PID,IsApproved,BranchId,ProvinceId")] AdminRequest adminRequest)
 {
     if (ModelState.IsValid)
     {
         db.Entry(adminRequest).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.BranchId   = new SelectList(db.Branches, "Id", "Code", adminRequest.BranchId);
     ViewBag.ProvinceId = new SelectList(db.Provinces, "Id", "Code", adminRequest.ProvinceId);
     return(View(adminRequest));
 }
Example #14
0
            public static QAdminRequest NormalView(AdminRequest p, QUser user)
            {
                return(p == null ? null : new QAdminRequest
                {
                    Id = p.Id,
                    TopicId = p.TopicId,
                    SenderId = p.SenderId,
                    Text = p.Text,
                    Status = p.Status,

                    User = user
                });
            }
Example #15
0
        // GET: AdminRequests/Details/5
        public ActionResult Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            AdminRequest adminRequest = db.AdminRequests.Find(id);

            if (adminRequest == null)
            {
                return(HttpNotFound());
            }
            return(View(adminRequest));
        }
Example #16
0
        public async Task <ActionResult> TermNotes(AdminRequest model)
        {
            ValidateRequest(model, _adminSettings);
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            _dataService.CleanTermNotes();

            var categories = _dataService.FetchNoteCategories();
            var subjects   = categories.SelectMany(x => x.SubItems).ToList();


            foreach (var subject in subjects)
            {
                if (subject.SubItems.HasItems())
                {
                    foreach (var term in subject.SubItems)
                    {
                        var selectedTerm = _termsService.GetById(term.Id);
                        await SaveTermNotes(selectedTerm);
                    }
                }
                else
                {
                    Subject selectedSubject = await _subjectsService.GetByIdAsync(subject.Id);

                    int parent = -1;
                    //科目底下所有條文
                    var terms   = (await _termsService.FetchAsync(selectedSubject, parent)).Where(x => !x.ChapterTitle);
                    var termIds = terms.Select(x => x.Id).ToList();

                    if (terms.HasItems())
                    {
                        _termsService.LoadSubItems(terms);
                        terms = terms.GetOrdered();

                        foreach (var term in terms)
                        {
                            await SaveTermNotes(term);
                        }
                    }
                }
            }

            return(Ok());
        }
Example #17
0
        // GET: AdminRequests/Edit/5
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            AdminRequest adminRequest = db.AdminRequests.Find(id);

            if (adminRequest == null)
            {
                return(HttpNotFound());
            }
            ViewBag.BranchId   = new SelectList(db.Branches, "Id", "Code", adminRequest.BranchId);
            ViewBag.ProvinceId = new SelectList(db.Provinces, "Id", "Code", adminRequest.ProvinceId);
            return(View(adminRequest));
        }
        private List <AdminRequest> ReadRequests(DataTable dataTable)
        {
            List <AdminRequest> requests = new List <AdminRequest>();

            foreach (DataRow dr in dataTable.Rows)
            {
                AdminRequest request = new AdminRequest()
                {
                    AdminRequestId = (int)dr["admin_request_id"],
                    Username       = (String)dr["user_username"],
                    UserId         = (int)dr["user_id"]
                };
                requests.Add(request);
            }
            return(requests);
        }
        public JsonResult Index()
        {
            //var redisDatabase = connection.GetDatabase();

            //redisDatabase.StringSet("kkk", "12345679++");

            //return Json(context.Admin.Pagination(1,10).ToList());

            AdminRequest request = new AdminRequest();

            request.Account  = "admin01";
            request.Password = "******";
            Service.Shared.BaseModel <AdminResponse> model = new Service.Shared.BaseModel <AdminResponse>();

            //adminService.Login(model, request);

            return(Json(model));
        }
Example #20
0
        public async Task <IActionResult> SendAdminRequest([FromBody] SendAdminRequestModel model)
        {
            var topicId = XUtils.ParseId(model.TopicId);

            // Topic is group topic
            var topic = await Context.Topics.FirstOrDefaultAsync(p => p.Id == topicId);

            if (topic == null)
            {
                return(new ApiError(MyErrorCode.IdNotFound, "Topic id not found").Wrap());
            }
            if (topic.IsGroup == false)
            {
                return(new ApiError(MyErrorCode.TypeMismatch, "This topic is not group").Wrap());
            }

            // should be normal member
            var member = await Context.TopicMembers.FirstOrDefaultAsync(p => p.TopicId == topicId && p.UserId == AuthStore.UserId);

            if (member?.Role != MemberRole.Normal)
            {
                return(new ApiError(MyErrorCode.RoleMismatch, "You are not normal row of the topic").Wrap());
            }

            // unhandled request exist?
            var previous = await Context.AdminRequests.FirstOrDefaultAsync(
                p => p.TopicId == topicId && p.SenderId == AuthStore.UserId && p.Status == RequestStatus.Unhandled);

            if (previous != null)
            {
                return(new ApiError(MyErrorCode.ExistUnhandledReuqest, "你已经发送过请求,但未被处理").Wrap());
            }

            // send request
            var request = new AdminRequest(topicId.Value, AuthStore.UserId.Value, model.Text);

            await Context.AddAsync(request);

            await Context.GoAsync();

            return(Ok(new IdResponse(request.Id)));
        }
        public async Task <ActionResult> DbBackups([FromBody] AdminRequest model)
        {
            ValidateRequest(model, _adminSettings);
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var    folderPath    = BackupFolder(_adminSettings);
            string storageFolder = DateTime.Today.ToDateNumber().ToString();

            foreach (var filePath in Directory.GetFiles(folderPath))
            {
                var fileInfo = new FileInfo(filePath);
                await _cloudStorageService.UploadFileAsync(filePath, $"{storageFolder}/{fileInfo.Name}");
            }


            return(Ok());
        }
        public void Login(BaseModel <AdminResponse> model, AdminRequest request)
        {
            DAO.Request.AdminRequest request2 = new DAO.Request.AdminRequest();
            request2.Account = request.Account;

            String password = SHA.SHA1(request.Password);

            DAO.Shared.BaseModel <List <DAO.Response.AdminResponse> > model2 = new DAO.Shared.BaseModel <List <DAO.Response.AdminResponse> >();

            /* 獲取資料 */
            adminDAO.Get(model2, request2);

            if (!model2.Success || model2.Result.Count != 1 || !password.Equals(model2.Result[0].Password))
            {
                return;
            }

            model.Success = true;
            model.Result  = Mapper(model2.Result[0]);
        }
Example #23
0
 public AdminResponse AdminRegistration(AdminRequest adminRequest)
 {
     try
     {
         var data = this.dBContext.admins.FirstOrDefault(linq => linq.AdmEmail == adminRequest.AdminEmail);
         if (data != null)
         {
             return(null);
         }
         adminRequest.Password = EncodeDecode.EncodePassword(adminRequest.Password);
         Admin admin = new Admin()
         {
             AdmFirstName     = adminRequest.AdminFirstName,
             AdmLastName      = adminRequest.AdminLastName,
             AdmContactNumber = adminRequest.AdminContactNumber,
             AdmEmail         = adminRequest.AdminEmail,
             Created          = DateTime.Now,
             Modified         = DateTime.Now,
             Password         = adminRequest.Password
         };
         this.dBContext.admins.Add(admin);
         dBContext.SaveChanges();
         if (adminRequest != null)
         {
             AdminResponse adminResponse = new AdminResponse()
             {
                 AdminId            = admin.AdminId,
                 AdminFirstName     = admin.AdmFirstName,
                 AdminLastName      = admin.AdmLastName,
                 AdminContactNumber = admin.AdmContactNumber,
                 AdminEmail         = admin.AdmEmail,
             };
             return(adminResponse);
         }
         return(null);
     }
     catch (Exception e)
     {
         throw new Exception(e.Message);
     }
 }
Example #24
0
        public async Task <ActionResult> StoreYearRecruits(AdminRequest model)
        {
            ValidateRequest(model, _adminSettings);
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            int parent   = 0;
            var recruits = await _recruitsService.FetchAsync(parent);

            recruits = recruits.Where(x => x.Active).GetOrdered();

            _recruitsService.LoadSubItems(recruits);

            var recruitViews = recruits.MapViewModelList(_mapper);

            foreach (var yearView in recruitViews)
            {
                foreach (var recruitView in yearView.SubItems)
                {
                    recruitView.QuestionIds = _questionsService.FetchQuestionIdsByRecruit(new Recruit {
                        Id = recruitView.Id
                    }).ToList();

                    foreach (var partView in recruitView.SubItems)
                    {
                        partView.QuestionIds = _questionsService.FetchQuestionIdsByRecruit(new Recruit {
                            Id = partView.Id
                        }).ToList();
                    }
                }
            }


            _dataService.SaveYearRecruits(recruitViews);

            return(Ok());
        }
Example #25
0
        public async Task <ActionResult> NoteCategories(AdminRequest model)
        {
            ValidateRequest(model, _adminSettings);
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var allSubjects = await _subjectsService.FetchAsync();

            allSubjects = allSubjects.Where(x => x.Active);

            var allTerms = await _termsService.FetchAllAsync();

            var rootSubjects = allSubjects.Where(x => x.ParentId < 1).GetOrdered();

            var categories = rootSubjects.Select(item => item.MapNoteCategoryViewModel()).ToList();

            foreach (var root in categories)
            {
                int parentId = root.Id;
                var subjects = allSubjects.Where(x => x.ParentId == parentId).GetOrdered();
                root.SubItems = subjects.Select(item => item.MapNoteCategoryViewModel(parentId)).ToList();
            }

            var subjectCategories = categories.SelectMany(x => x.SubItems);

            //只到ChapterTitle, 捨棄Hide項目
            foreach (var subjectCategory in subjectCategories)
            {
                var terms = allTerms.Where(item => item.SubjectId == subjectCategory.Id && item.ParentId == 0 && item.ChapterTitle && !item.Hide).GetOrdered();
                subjectCategory.SubItems = terms.Select(item => item.MapNoteCategoryViewModel()).ToList();
            }

            _dataService.SaveNoteCategories(categories);

            return(Ok());
        }
Example #26
0
        public IActionResult AdminRegistration([FromBody] AdminRequest adminRequest)
        {
            try
            {
                bool   status;
                string message;

                var data = this.adminBusiness.AdminRegistration(adminRequest);
                if (data != null)
                {
                    status  = true;
                    message = "Admin registered successfully";
                    return(this.Ok(new { status, message, data }));
                }
                status  = false;
                message = "Email already exists";
                return(this.BadRequest(new { status, message }));
            }
            catch (Exception e)
            {
                return(this.BadRequest(e.Message));
            }
        }
Example #27
0
        public IActionResult ConfirmSend()
        {
            var CurrentUser     = _context.Users.Find(userManager.GetUserId(User));
            var SiteOwner       = _AdminRequestStore.GetSiteOwner();
            var AdminRequestBox = _AdminRequestStore.GetAdminBox(SiteOwner.Id);
            var RequestUser     = new AdminRequestor()
            {
                Username = CurrentUser.UserName,
                UserId   = CurrentUser.Id,
            };

            _AdminRequestStore.AddRequestor(RequestUser);
            var Request = new AdminRequest()
            {
                Username         = CurrentUser.UserName,
                RequestDate      = DateTime.Now,
                ApprovalBoxId    = AdminRequestBox.Id,
                AdminRequestorId = RequestUser.Id
            };

            _AdminRequestStore.AddRequest(Request);
            _context.SaveChanges();
            return(RedirectToAction(ActionName.Profile, ControllerName.Accounts));
        }
        public JsonResult Login([FromBody] AdminViewModel <String> data)
        {
            BaseModel <AdminResponse> model = new BaseModel <AdminResponse>();
            AdminRequest request            = new AdminRequest();

            request.Account  = data.Account;
            request.Password = data.Password;

            adminService.Login(model, request);

            if (model.Success)
            {
                UserDataKeepViewModel userData = new UserDataKeepViewModel();
                userData.Id   = model.Result.Id;
                userData.Name = model.Result.Name;

                manage.data = userData;

                data.Success = true;
                data.Result  = manage.UserDataEncrypt();
            }

            return(Json(data));
        }
Example #29
0
        public ServiceRes IsAdminValid(AdminRequest adminRequest)
        {
            ServiceRes serviceRes = new ServiceRes();

            try
            {
                SqlParameter[] parameter = new SqlParameter[2];
                parameter[0] = new SqlParameter {
                    ParameterName = "@username", Value = adminRequest.Username
                };
                parameter[1] = new SqlParameter {
                    ParameterName = "@password", Value = adminRequest.Password
                };
                var adminDt = SqlHelper.GetTableFromSP("Usp_AdminLogin", parameter);
                if (adminDt.Rows.Count > 0)
                {
                    if (Convert.ToString(adminDt.Rows[0][0]) == "0")
                    {
                        serviceRes.IsSuccess  = true;
                        serviceRes.ReturnCode = "200";
                        serviceRes.ReturnMsg  = "Success";
                    }
                    else
                    {
                        serviceRes.IsSuccess  = false;
                        serviceRes.ReturnCode = "400";
                        serviceRes.ReturnMsg  = "Invalid username and password";
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.WriteLog(ex);
            }
            return(serviceRes);
        }
        public void Get(BaseModel <List <AdminResponse> > model, AdminRequest request)
        {
            if (onlineCustomerServiceContext == null)
            {
                return;
            }

            IQueryable <Admin> queryable = onlineCustomerServiceContext.Admin.Where(
                admin =>
                (String.IsNullOrWhiteSpace(request.Account) || admin.Account.Equals(request.Account))
                );

            Int32 pageCount             = queryable.Count();
            List <AdminResponse> result = new List <AdminResponse>();

            foreach (Admin admin in queryable.Pagination(model.PageIndex, model.PageSize))
            {
                result.Add(Mapper(admin));
            }

            model.Success   = true;
            model.PageCount = pageCount;
            model.Result    = result;
        }