コード例 #1
0
ファイル: SmsSender.cs プロジェクト: gsaadeh/AspNetCoreSpa
        public async Task <bool> SendSmsTwillioAsync(string number, string message)
        {
            try
            {
                // https://www.elanderson.net/2016/03/sms-using-twilio-rest-api-in-asp-net-core/
                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                                                                                               Convert.ToBase64String(Encoding.ASCII.GetBytes($"{_smsSettings.Sid}:{_smsSettings.Token}")));

                    var content = new FormUrlEncodedContent(new[]
                    {
                        // Either +44ukmobile OR ukmobile (07456432132)
                        new KeyValuePair <string, string>("To", $"{number}"),
                        new KeyValuePair <string, string>("From", _smsSettings.From),
                        new KeyValuePair <string, string>("Body", message)
                    });

                    var response = await client.PostAsync(_smsSettings.RequestUrl, content).ConfigureAwait(false);

                    return(response.IsSuccessStatusCode);
                }
            }
            catch (Exception ex)
            {
                _loggingRepository.Add(new Error
                {
                    Message    = ex.Message,
                    StackTrace = ex.StackTrace
                });
                _loggingRepository.Commit();

                return(false);
            }
        }
コード例 #2
0
        public async Task <IActionResult> Login([FromBody] LoginViewModel user)
        {
            IActionResult _result = new ObjectResult(false);
            GenericResult _authenticationResult = null;

            try
            {
                MembershipContext _userContext = _membershipService.ValidateUser(user.Username, user.Password);

                if (_userContext.User != null)
                {
                    IEnumerable <Role> _roles  = _userRepository.GetUserRoles(user.Username);
                    List <Claim>       _claims = new List <Claim>();
                    foreach (Role role in _roles)
                    {
                        Claim _claim = new Claim(ClaimTypes.Role, "Admin", ClaimValueTypes.String, user.Username);
                        _claims.Add(_claim);
                    }

                    await HttpContext.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                                                                 new ClaimsPrincipal(new ClaimsIdentity(_claims, CookieAuthenticationDefaults.AuthenticationScheme)),
                                                                 new Microsoft.AspNetCore.Http.Authentication.AuthenticationProperties {
                        IsPersistent = user.RememberMe
                    });


                    _authenticationResult = new AuthResult()
                    {
                        Succeeded = true,
                        UserId    = _userRepository.GetSingleByUsername(user.Username).Id,
                        Message   = "Authentication succeeded"
                    };
                }
                else
                {
                    _authenticationResult = new GenericResult()
                    {
                        Succeeded = false,
                        Message   = "Authentication failed"
                    };
                }
            }
            catch (Exception ex)
            {
                _authenticationResult = new GenericResult()
                {
                    Succeeded = false,
                    Message   = ex.Message
                };

                _loggingRepository.Add(new Error()
                {
                    Message = ex.Message, StackTrace = ex.StackTrace, DateCreated = DateTime.Now
                });
                _loggingRepository.Commit();
            }

            _result = new ObjectResult(_authenticationResult);
            return(_result);
        }
コード例 #3
0
ファイル: UserController.cs プロジェクト: marcinv1t0/ZTW2
        public IActionResult Delete(int id)
        {
            IActionResult _result       = new ObjectResult(false);
            GenericResult _removeResult = null;

            try
            {
                Offer _offerToRemove = this._offerRepository.GetSingle(id);
                this._offerRepository.Delete(_offerToRemove);
                this._offerRepository.Commit();

                _removeResult = new GenericResult()
                {
                    Succeeded = true,
                    Message   = "Offer removed."
                };
            }
            catch (Exception ex)
            {
                _removeResult = new GenericResult()
                {
                    Succeeded = false,
                    Message   = ex.Message
                };

                _loggingRepository.Add(new Error()
                {
                    Message = ex.Message, StackTrace = ex.StackTrace, DateCreated = DateTime.Now
                });
                _loggingRepository.Commit();
            }

            _result = new ObjectResult(_removeResult);
            return(_result);
        }
コード例 #4
0
        public async Task <IActionResult> Get(int?page, int?pageSize)
        {
            PaginationSet <AlbumViewModel> pagedSet = new PaginationSet <AlbumViewModel>();

            try
            {
                if (await _authorizationService.AuthorizeAsync(User, "AdminOnly"))
                {
                    int currentPage     = page.Value;
                    int currentPageSize = pageSize.Value;

                    List <Album> _albums = null;

                    //记录Album的总数量
                    int _totalAlbums = new int();

                    _albums = _albumRepository
                              .AllIncluding(t => t.Photos)
                              .OrderBy(t => t.Id)
                              .Skip(currentPage * currentPageSize)
                              .Take(currentPageSize)
                              .ToList();

                    _totalAlbums = _albumRepository.GetAll().Count();

                    //转换成ViewModel
                    IEnumerable <AlbumViewModel> _albumsVM = Mapper.Map <IEnumerable <Album>, IEnumerable <AlbumViewModel> >(_albums);

                    //转换成分页
                    pagedSet = new PaginationSet <AlbumViewModel>()
                    {
                        Page       = currentPage,
                        TotalCount = _totalAlbums,
                        TotalPages = (int)Math.Ceiling((decimal)_totalAlbums / currentPageSize),
                        Items      = _albumsVM
                    };
                }
                else
                {
                    CodeResultStatus _codeResult = new CodeResultStatus(401);
                    return(new ObjectResult(_codeResult));
                }
            }
            catch (Exception ex)
            {
                _loggingRepository.Add(new Error()
                {
                    Message     = ex.Message,
                    StackTrace  = ex.StackTrace,
                    DateCreated = DateTime.Now
                });

                _loggingRepository.Commit();
            }

            return(new ObjectResult(pagedSet));
        }
コード例 #5
0
        // [Authorize(Roles = "AddUserGroup")]
        public IActionResult Create([FromBody] ApplicationGroupViewModel appGroupViewModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            IActionResult result    = new ObjectResult(false);
            GenericResult addResult = null;

            try
            {
                var newAppGroup = new ApplicationGroup();
                newAppGroup.Name = appGroupViewModel.Name;
                var appGroup = _appGroupService.Add(newAppGroup);
                _appGroupService.Save();

                //save group
                var listRoleGroup = new List <ApplicationRoleGroup>();
                var roles         = appGroupViewModel.Roles.Where(x => x.Check).ToList();
                foreach (var role in roles)
                {
                    listRoleGroup.Add(new ApplicationRoleGroup()
                    {
                        GroupId = appGroup.Entity.ID,
                        RoleId  = role.Id
                    });
                }
                _appRoleService.AddRolesToGroup(listRoleGroup, appGroup.Entity.ID);
                _appRoleService.Save();


                addResult = new GenericResult()
                {
                    Succeeded = true,
                    Message   = "Thêm nhóm người dùng thành công"
                };
            }
            catch (Exception ex)
            {
                addResult = new GenericResult()
                {
                    Succeeded = false,
                    Message   = ex.Message
                };

                _loggingRepository.Add(new Error()
                {
                    Message = ex.Message, StackTrace = ex.StackTrace, DateCreated = DateTime.Now
                });
                _loggingRepository.Commit();
            }

            result = new ObjectResult(addResult);
            return(result);
        }
コード例 #6
0
ファイル: AlbumsController.cs プロジェクト: vutung189/btl
        public async Task <IActionResult> Get(int?page, int?pageSize)
        {
            PaginationSet <AlbumViewModel> pagedSet = new PaginationSet <AlbumViewModel>();

            try
            {
                if (await _authorizationService.AuthorizeAsync(User, "AdminOnly"))
                {
                    int currentPage     = page.Value;
                    int currentPageSize = pageSize.Value;

                    List <Album> _albums      = null;
                    int          _totalAlbums = new int();
                    var          username     = Request.Cookies["user"];
                    User         user         = _userRepository.GetSingleByUsername(username);
                    int          user_id      = user.Id;

                    _albums = _albumRepository
                              .AllIncluding(a => a.Photos)
                              .OrderBy(a => a.Id)
                              .Where(s => s.User_ID == user_id)
                              .Skip(currentPage * currentPageSize)
                              .Take(currentPageSize)
                              .ToList();

                    _totalAlbums = _albumRepository.GetAll().Count();

                    IEnumerable <AlbumViewModel> _albumsVM = Mapper.Map <IEnumerable <Album>, IEnumerable <AlbumViewModel> >(_albums);

                    pagedSet = new PaginationSet <AlbumViewModel>()
                    {
                        Page       = currentPage,
                        TotalCount = _totalAlbums,
                        TotalPages = (int)Math.Ceiling((decimal)_totalAlbums / currentPageSize),
                        Items      = _albumsVM
                    };
                }
                else
                {
                    CodeResultStatus _codeResult = new CodeResultStatus(401);
                    return(new ObjectResult(_codeResult));
                }
            }
            catch (Exception ex)
            {
                _loggingRepository.Add(new Error()
                {
                    Message = ex.Message, StackTrace = ex.StackTrace, DateCreated = DateTime.Now
                });
                _loggingRepository.Commit();
            }

            return(new ObjectResult(pagedSet));
        }
コード例 #7
0
        public async Task <IActionResult> Get()
        {
            // PaginationSet<OfferViewModel> pagedSet = new PaginationSet<OfferViewModel>();
            List <Offer> _offers = null;

            try
            {
                //if (await _authorizationService.AuthorizeAsync(User, "AdminOnly"))
                //{
                //int currentPage = page.Value;
                //int currentPageSize = pageSize.Value;

                int _totalOffers = new int();


                /*_offers = _offerRepository
                 *  .OrderBy(a => a.StartTime)
                 *  //.Skip(currentPage * currentPageSize)
                 *  //Take(currentPageSize)
                 *  .ToList();*/

                _offers = _offerRepository.GetAll().ToList();

                _totalOffers = _offerRepository.GetAll().Count();

                IEnumerable <OfferViewModel> _offersVM = Mapper.Map <IEnumerable <Offer>, IEnumerable <OfferViewModel> >(_offers);

                /* pagedSet = new PaginationSet<OfferViewModel>()
                 * {
                 *   Page = currentPage,
                 *   TotalCount = _totalOffers,
                 *   TotalPages = (int)Math.Ceiling((decimal)_totalOffers / currentPageSize),
                 *   Items = _offersVM
                 * };*/
                //}

                /*   else
                 * {
                 *     CodeResultStatus _codeResult = new CodeResultStatus(401);
                 *     return new ObjectResult(_codeResult);
                 * } */
            }
            catch (Exception ex)
            {
                _loggingRepository.Add(new Error()
                {
                    Message = ex.Message, StackTrace = ex.StackTrace, DateCreated = DateTime.Now
                });
                _loggingRepository.Commit();
            }

            return(new ObjectResult(_offers));
        }
コード例 #8
0
        //  [Authorize(Roles = "AddRole")]
        public async Task <IActionResult> Create([FromBody] ApplicationRoleViewModel applicationRoleViewModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            IActionResult result    = new ObjectResult(false);
            GenericResult addResult = null;

            try
            {
                // var newAppRole = new ApplicationRole();
                // newAppRole.UpdateApplicationRole(applicationRoleViewModel);
                //_appRoleService.Add(newAppRole);
                // _appRoleService.Save();

                var adminRole = await _roleManager.FindByNameAsync(applicationRoleViewModel.Name);

                if (adminRole == null)
                {
                    adminRole = new IdentityRole(applicationRoleViewModel.Name);
                    await _roleManager.CreateAsync(adminRole);
                }


                addResult = new GenericResult()
                {
                    Succeeded = true,
                    Message   = "Thêm role thành công"
                };
            }
            catch (Exception ex)
            {
                addResult = new GenericResult()
                {
                    Succeeded = false,
                    Message   = "Thêm role thất bại. Lỗi " + ex
                };

                _loggingRepository.Add(new Error()
                {
                    Message = ex.Message, StackTrace = ex.StackTrace, DateCreated = DateTime.Now
                });
                _loggingRepository.Commit();
            }

            result = new ObjectResult(addResult);
            return(result);
        }
コード例 #9
0
        public PaginationSet <PhotoViewModel> Get(int?page, int?pageSize)
        {
            PaginationSet <PhotoViewModel> pagedSet = null;

            try
            {
                int currentPage     = page.Value;
                int currentPageSize = pageSize.Value;

                List <Photo> _photos           = null;
                int          _totalPhotosCount = new int();

                _photos = _photoRepository
                          .AllIncluding(t => t.Album)
                          .OrderBy(t => t.Id)
                          .Skip(currentPage * currentPageSize)
                          .Take(currentPageSize)
                          .Take(currentPageSize)
                          .ToList();

                _totalPhotosCount = _photoRepository.GetAll().Count();

                //准备ViewModel
                IEnumerable <PhotoViewModel> _photosVM = Mapper.Map <IEnumerable <Photo>, IEnumerable <PhotoViewModel> >(_photos);

                //准备为分页的模型
                pagedSet = new PaginationSet <PhotoViewModel>()
                {
                    Page       = currentPage,
                    TotalCount = _totalPhotosCount,
                    TotalPages = (int)Math.Ceiling((decimal)_totalPhotosCount / currentPageSize),
                    Items      = _photosVM
                };
            }
            catch (Exception ex)
            {
                _loggingRepository.Add(new Error()
                {
                    Message     = ex.Message,
                    StackTrace  = ex.StackTrace,
                    DateCreated = DateTime.Now
                });

                _loggingRepository.Commit();
            }

            return(pagedSet);
        }
コード例 #10
0
        public PaginationSet <PhotoViewModel> Get(int?page, int?pageSize)
        {
            PaginationSet <PhotoViewModel> pagedSet = null;

            try
            {
                int currentPage     = page.Value;
                int currentPageSize = pageSize.Value;

                List <Photo> _photos      = null;
                int          _totalPhotos = new int();

                _photos = _photoRepository
                          .AllIncluding(p => p.Album)
                          .OrderByDescending(p => p.Rating)
                          .Skip(currentPage * currentPageSize)
                          .Take(currentPageSize)
                          .ToList();

                var albums = _albumRepository.AllIncluding(a => a.User).ToList();
                foreach (var photo in _photos)
                {
                    photo.Album.User = albums.FirstOrDefault(a => a.Id == photo.AlbumId).User;
                }

                _totalPhotos = _photoRepository.GetAll().Count();

                IEnumerable <PhotoViewModel> _photosVM = Mapper.Map <IEnumerable <Photo>, IEnumerable <PhotoViewModel> >(_photos);

                pagedSet = new PaginationSet <PhotoViewModel>()
                {
                    Page       = currentPage,
                    TotalCount = _totalPhotos,
                    TotalPages = (int)Math.Ceiling((decimal)_totalPhotos / currentPageSize),
                    Items      = _photosVM
                };
            }
            catch (Exception ex)
            {
                _loggingRepository.Add(new Error()
                {
                    Message = ex.Message, StackTrace = ex.StackTrace, DateCreated = DateTime.Now
                });
                _loggingRepository.Commit();
            }

            return(pagedSet);
        }
コード例 #11
0
        public IActionResult Delete(int id)
        {
            IActionResult _result       = new ObjectResult(false);
            GenericResult _removeResult = null;

            try
            {
                WalkSight _walkSightToRemove = this._walkSightRepository.GetSingle(id);
                this._walkSightRepository.Delete(_walkSightToRemove);
                this._walkSightRepository.Commit();

                _removeResult = new GenericResult()
                {
                    Succeeded = true,
                    Message   = "Sight is removed from the walk."
                };
            }
            catch (Exception ex)
            {
                _removeResult = new GenericResult()
                {
                    Succeeded = false,
                    Message   = ex.Message
                };

                _loggingRepository.Add(new Error()
                {
                    Message = ex.Message, StackTrace = ex.StackTrace, CreatedDate = DateTime.Now
                });
                _loggingRepository.Commit();
            }

            _result = new ObjectResult(_removeResult);
            return(_result);
        }
コード例 #12
0
        public async Task <IActionResult> Login([FromBody] LoginViewModel user)
        {
            IActionResult _result = new ObjectResult(false);
            GenericResult _authenticationResult = null;

            try
            {
                DEFACEWEBSITEContext context = new DEFACEWEBSITEContext();
                string password = MD5Encoder.MD5Hash(user.Password);
                string command  = $"dbo.Users_CheckLogin @p_USERNAME = '******',@p_PASSWORD='******',@p_TOKEN='{null}'";
                var    result   = await context.Database.ExecuteSqlCommandAsync(command, cancellationToken : CancellationToken.None);

                if (result == 1)
                {
                    _authenticationResult = new GenericResult()
                    {
                        Succeeded = true,
                        Message   = "Authentication succeeded"
                    };
                }
                else
                {
                    _authenticationResult = new GenericResult()
                    {
                        Succeeded = false,
                        Message   = "Authentication failed"
                    };
                }
            }
            catch (Exception ex)
            {
                _authenticationResult = new GenericResult()
                {
                    Succeeded = false,
                    Message   = ex.Message
                };

                _loggingRepository.Add(new Error()
                {
                    Message = ex.Message, StackTrace = ex.StackTrace, DateCreated = DateTime.Now
                });
                _loggingRepository.Commit();
            }

            _result = new ObjectResult(_authenticationResult);
            return(_result);
        }
コード例 #13
0
        public PaginationSet <PhotoViewModel> Get(int?page, int?pageSize)
        {
            PaginationSet <PhotoViewModel> pagedSet = null;

            try
            {
                int currentPage     = page.Value;
                int currentPageSize = pageSize.Value;

                List <Photo> _photos      = null;
                int          _totalPhotos = new int();


                _photos = _photoRepository
                          .AllIncluding(p => p.Album)
                          .OrderBy(p => p.Id)
                          .Skip(currentPage * currentPageSize)
                          .Take(currentPageSize)
                          .ToList();

                _totalPhotos = _photoRepository.GetAll().Count();

                IEnumerable <PhotoViewModel> _photosVM = Mapper.Map <IEnumerable <Photo>, IEnumerable <PhotoViewModel> >(_photos);

                _logger.LogInformation("Photo action requested at {Default} or {$ToString} or {@Object}", _photosVM, _photosVM, _photosVM);

                pagedSet = new PaginationSet <PhotoViewModel>()
                {
                    Page       = currentPage,
                    TotalCount = _totalPhotos,
                    TotalPages = (int)Math.Ceiling((decimal)_totalPhotos / currentPageSize),
                    Items      = _photosVM
                };
            }
            catch (Exception ex)
            {
                _loggingRepository.Add(new Error()
                {
                    Message = ex.Message, StackTrace = ex.StackTrace, DateCreated = DateTime.Now
                });
                _loggingRepository.Commit();
            }

            return(pagedSet);
        }
コード例 #14
0
        public IActionResult Post([FromBody] User user)
        {
            IActionResult result     = new ObjectResult(false);
            GenericResult editResult = null;

            var authenticationHeader = Request?.Headers["Authorization"];
            var token   = authenticationHeader?.FirstOrDefault().Split(' ')[1];
            var jwt     = new JwtSecurityToken(token);
            var subject = jwt.Subject;
            var dbUser  = _userRepository.GetSingleByUsername(subject);

            user.HashedPassword = dbUser.HashedPassword;
            user.Salt           = dbUser.Salt;
            if (user.Photo == "images/" || user.Photo == "")
            {
                user.Photo = dbUser.Photo;
            }
            try
            {
                _userRepository.Edit(user);
                _userRepository.Commit();
                editResult = new GenericResult()
                {
                    Succeeded = true,
                    Message   = "User updated."
                };
            }
            catch (Exception ex)
            {
                editResult = new GenericResult()
                {
                    Succeeded = false,
                    Message   = ex.Message + user.Photo
                };
                _loggingRepository.Add(new Error()
                {
                    Message     = ex.Message,
                    StackTrace  = ex.StackTrace,
                    DateCreated = DateTime.Now
                });
                _loggingRepository.Commit();
            }
            result = new ObjectResult(editResult);
            return(result);
        }
コード例 #15
0
        public void Log(string message, string detail = "", LogLevels logLevel = LogLevels.Spam, LogSource source = LogSource.UNKNOWN)
        {
            LogEntry log = new LogEntry {
                Timestamp = DateTime.UtcNow, Detail = detail, Message = message, LogLevelId = Convert.ToInt32(logLevel), LogType = source.ToString(), HostName = Environment.MachineName
            };

            _loggingRepository.Add(log);
            _loggingRepository.Commit();
        }
コード例 #16
0
    public async Task <IActionResult> Get(int?page, int?pageSize)
    {
        PaginationSet <AlbumViewModel> pagedSet = new PaginationSet <AlbumViewModel>();

        try
        {
            int currentPage     = page.Value;
            int currentPageSize = pageSize.Value;

            List <Album> _albums      = null;
            int          _totalAlbums = new int();


            _albums = _albumRepository
                      .AllIncluding(a => a.Photos)
                      .OrderBy(a => a.Id)
                      .Skip(currentPage * currentPageSize)
                      .Take(currentPageSize)
                      .ToList();

            _totalAlbums = _albumRepository.GetAll().Count();

            IEnumerable <AlbumViewModel> _albumsVM = Mapper.Map <IEnumerable <Album>, IEnumerable <AlbumViewModel> >(_albums);

            pagedSet = new PaginationSet <AlbumViewModel>()
            {
                Page       = currentPage,
                TotalCount = _totalAlbums,
                TotalPages = (int)Math.Ceiling((decimal)_totalAlbums / currentPageSize),
                Items      = _albumsVM
            };
        }
        catch (Exception ex)
        {
            _loggingRepository.Add(new Error()
            {
                Message = ex.Message, StackTrace = ex.StackTrace, DateCreated = DateTime.Now
            });
            _loggingRepository.Commit();
        }

        return(new ObjectResult(pagedSet));
    }
コード例 #17
0
        public PaginationSet <BoulderViewModel> Get(int?page, int?pageSize)
        {
            PaginationSet <BoulderViewModel> pagedSet = new PaginationSet <BoulderViewModel>();

            try
            {
                int currentPage     = page.Value;
                int currentPageSize = pageSize.Value;

                List <Boulder> _boulders      = null;
                int            _totalBoulders = new int();

                _boulders = _boulderRepository
                            .AllIncluding(a => a.Problems)
                            .OrderBy(a => a.Id)
                            .Skip(currentPage * currentPageSize)
                            .Take(currentPageSize)
                            .ToList();

                _totalBoulders = _boulderRepository.GetAll().Count();

                IEnumerable <BoulderViewModel> _bouldersVM = Mapper.Map <IEnumerable <Boulder>, IEnumerable <BoulderViewModel> >(_boulders);

                pagedSet = new PaginationSet <BoulderViewModel>()
                {
                    Page       = currentPage,
                    TotalCount = _totalBoulders,
                    TotalPages = (int)Math.Ceiling((decimal)_totalBoulders / currentPageSize),
                    Items      = _bouldersVM
                };
            }
            catch (Exception ex)
            {
                _loggingRepository.Add(new Error()
                {
                    Message = ex.Message, StackTrace = ex.StackTrace, DateCreated = DateTime.Now
                });
                _loggingRepository.Commit();
            }

            return(pagedSet);
        }
コード例 #18
0
        public async Task <IEnumerable <Message> > GetAll(int offset = 0)
        {
            var authenticationHeader = Request?.Headers["Authorization"];
            var token   = authenticationHeader?.FirstOrDefault().Split(' ')[1];
            var subject = _jwtFormater.GetSubject(token);
            var user    = _userRepository.GetSingleByUsername(subject);

            IEnumerable <Message> messages = new List <Message>();

            try
            {
                var chats = await _chatUserRepository.FindByAsync(cu => cu.UserId == user.Id);

                var chatIds = chats.Select(cu => cu.ChatId);
                messages = await _messageRepository.FindByAsync(message => chatIds.Contains(message.ChatId));

                messages = messages.ToList();
            }
            catch (Exception ex)
            {
                _loggingRepository.Add(new Error()
                {
                    Severity    = "Error",
                    Message     = ex.Message,
                    StackTrace  = ex.StackTrace,
                    DateCreated = DateTime.Now
                });
                _loggingRepository.Commit();
            }

            return(messages.Skip(messages.Count() - offset - 20).Take(20));
        }
コード例 #19
0
        public async Task <IActionResult> MeGet()
        {
            try
            {
                var user = await _userManager.FindByEmailAsync(HttpContext.User.Identity.Name);

                if (user != null)
                {
                    return(Ok(new { FirstName = user.FirstName, LastName = user.LastName }));
                }
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return(Json(ModelState.GetModelErrors()));
            }
            catch (Exception ex)
            {
                _loggingRepository.Add(new Error()
                {
                    Message = ex.Message, StackTrace = ex.StackTrace, DateCreated = DateTime.Now
                });
                _loggingRepository.Commit();

                return(BadRequest());
            }
        }
コード例 #20
0
        public PaginationSet <ProductViewModel> Get(int page, int pageSize)
        {
            PaginationSet <ProductViewModel> pagedSet = null;

            try
            {
                var products = _productRepository
                               .AllIncluding(p => p.ProductStatuses, p => p.ProductType)
                               .OrderBy(p => p.Name)
                               .Skip(page * pageSize)
                               .Take(pageSize)
                               .ToList();

                var totalCount = _productRepository.GetAll().Count();

                var viewModels = Mapper.Map <IEnumerable <Product>, IEnumerable <ProductViewModel> >(products);

                pagedSet = new PaginationSet <ProductViewModel>()
                {
                    Page       = page,
                    TotalCount = totalCount,
                    TotalPages = (int)Math.Ceiling((decimal)totalCount / pageSize),
                    Items      = viewModels
                };
            }
            catch (Exception ex)
            {
                _loggingRepository.Add(new Error()
                {
                    Message = ex.Message, StackTrace = ex.StackTrace, DateCreated = DateTime.Now
                });
                _loggingRepository.Commit();
            }

            return(pagedSet);
        }
コード例 #21
0
        public async Task <string> Get(int id)
        {
            string callbackFunctionName = Request.Query["callback"];
            string type       = Request.Query["type"];
            string sessionKey = Request.Query["sessionKey"];
            string jsCode     = callbackFunctionName + "({\"Status\":\"OK\"});";
            string wechatID   = "";
            string name       = "";
            string imageURL   = "";
            string barcode    = "";

            try
            {
                if (type.Equals("login"))
                {
                    wechatID = Request.Query["wechatID"];
                    name     = Request.Query["name"];
                    imageURL = Request.Query["imageURL"];
                    Wechat   wechat   = this._wechatService.CreateWechat(wechatID, name, imageURL);
                    Customer customer = this._customerService.CreateCustomer(name, name + "@netsdl.com", wechat.Id);
                    Session  session  = this._sessionService.CreateSession(sessionKey, customer.Id);
                }
                ;

                if (type.Equals("barcode"))
                {
                    barcode = Request.Query["barcode"];
                }

                var wechatModel = new WechatViewModel();
                wechatModel.SessionKey     = sessionKey;
                wechatModel.WechatName     = name;
                wechatModel.WechatImageUrl = imageURL;
                wechatModel.Barcode        = barcode;

                await Clients.Group("1").AddFeed(wechatModel);
            }
            catch (Exception ex)
            {
                _loggingRepository.Add(new Error()
                {
                    Message = ex.Message, StackTrace = ex.StackTrace, DateCreated = DateTime.Now
                });
                _loggingRepository.Commit();
            }

            return(jsCode);
        }
コード例 #22
0
        // Using https://github.com/jstedfast/MailKit
        public bool SendEmail(EmailModel model)
        {
            try
            {
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress(model.Subject, model.From));
                message.To.Add(new MailboxAddress("", model.To));
                message.Subject = model.Subject;

                message.Body = new TextPart("plain")
                {
                    Text = model.HtmlBody
                };

                using (var client = new SmtpClient())
                {
                    // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
                    client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                    client.Connect("smtp.gmail.com", 465, true);

                    // Note: since we don't have an OAuth2 token, disable
                    // the XOAUTH2 authentication mechanism.
                    client.AuthenticationMechanisms.Remove("XOAUTH2");

                    // Note: only needed if the SMTP server requires authentication
                    var user = Startup.Configuration["Email:SmtpLogin:Username"];
                    var pass = Startup.Configuration["Email:SmtpLogin:Password"];
                    client.Authenticate(user, pass);

                    client.Send(message);
                    client.Disconnect(true);
                    return(true);
                }
            }
            catch (Exception ex)
            {
                // if AuthenticationMechanismTooWeak: 5.7.14 , solution is to allow less secure apps
                // https://support.google.com/accounts/answer/6010255
                _loggingRepository.Add(new Error {
                    Message = ex.Message, StackTrace = ex.StackTrace
                });
                _loggingRepository.Commit();
                return(false);
            }
        }
コード例 #23
0
        public PaginationSet <UserViewModel> GetByWechatId(string wechatId)
        {
            PaginationSet <UserViewModel> pagedSet = null;

            try
            {
                int currentPage     = 0;
                int currentPageSize = 100;

                List <User> _users      = null;
                int         _totalUsers = new int();

                _users = _userRepository
                         .AllIncluding(p => p.Wechat)
                         .Where(p => p.Wechat.WechatId.Equals(wechatId))
                         .OrderBy(p => p.Id)
                         .Skip(currentPage * currentPageSize)
                         .Take(currentPageSize)
                         .ToList();

                _totalUsers = _userRepository.AllIncluding(p => p.Wechat).Where(p => p.WechatId.Equals(wechatId)).Count();

                IEnumerable <UserViewModel> _usersVM = Mapper.Map <IEnumerable <User>, IEnumerable <UserViewModel> >(_users);

                pagedSet = new PaginationSet <UserViewModel>()
                {
                    Page       = currentPage,
                    TotalCount = _totalUsers,
                    TotalPages = (int)Math.Ceiling((decimal)_totalUsers / currentPageSize),
                    Items      = _usersVM
                };
            }
            catch (Exception ex)
            {
                _loggingRepository.Add(new Error()
                {
                    Message = ex.Message, StackTrace = ex.StackTrace, DateCreated = DateTime.Now
                });
                _loggingRepository.Commit();
            }

            return(pagedSet);
        }
コード例 #24
0
        public PaginationSet <ProductViewModel> Get(int?storeId, int?page, int?pageSize)
        {
            PaginationSet <ProductViewModel> pagedSet = null;

            try
            {
                int currentPage     = page.Value;
                int currentPageSize = pageSize.Value;

                List <Product> _products      = null;
                int            _totalProducts = new int();

                _products = _productRepository
                            .AllIncluding(p => p.Store)
                            .Where(p => p.StoreId == storeId)
                            .OrderBy(p => p.Id)
                            .Skip(currentPage * currentPageSize)
                            .Take(currentPageSize)
                            .ToList();

                _totalProducts = _productRepository.FindBy(p => p.StoreId == storeId).Count();

                IEnumerable <ProductViewModel> _productsVM = Mapper.Map <IEnumerable <Product>, IEnumerable <ProductViewModel> >(_products);

                pagedSet = new PaginationSet <ProductViewModel>()
                {
                    Page       = currentPage,
                    TotalCount = _totalProducts,
                    TotalPages = (int)Math.Ceiling((decimal)_totalProducts / currentPageSize),
                    Items      = _productsVM
                };
            }
            catch (Exception ex)
            {
                _loggingRepository.Add(new Error()
                {
                    Message = ex.Message, StackTrace = ex.StackTrace, DateCreated = DateTime.Now
                });
                _loggingRepository.Commit();
            }

            return(pagedSet);
        }
コード例 #25
0
        public IActionResult VerifyPassword(int userId, string password)
        {
            IActionResult _result = new ObjectResult(false);
            GenericResult _authenticationResult = null;

            try
            {
                var user = _empluser.GetUserById(userId);

                var isValid = _empluser.IsPasswordValid(user, password);

                if (isValid)
                {
                    return(new OkObjectResult(true));
                }
                else
                {
                    return(new OkObjectResult(false));
                }
            }
            catch (Exception ex)
            {
                _authenticationResult = new GenericResult()
                {
                    Succeeded = false,
                    Message   = ex.Message
                };

                _loggingRepository.Add(new Error()
                {
                    Message = ex.Message, StackTrace = ex.StackTrace
                });
                _loggingRepository.Commit();
            }

            _result = new ObjectResult(_authenticationResult);
            return(_result);
        }
コード例 #26
0
        public async Task Invoke(HttpContext context)
        {
            var request = context.Request;

            try
            {
                if (!context.User.Identities.Any(identity => identity.IsAuthenticated))
                {
                    Claim claim = new Claim(ClaimTypes.Role, "Admin", ClaimValueTypes.String, "chsakell");
                    await context.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                                                             new ClaimsPrincipal(new ClaimsIdentity(new[] { claim }, CookieAuthenticationDefaults.AuthenticationScheme)));
                }
            }
            catch (Exception ex)
            {
                //   _loggingRepository.Add(new Error() { Message = ex.Message, StackTrace = ex.StackTrace, DateCreated = DateTime.Now });
                _loggingRepository.Commit();
            }

            await _next.Invoke(context);
        }
コード例 #27
0
        public async Task <IActionResult> Create([FromBody] ApplicationUserViewModel applicationUserViewModel)
        {
            //    await roleManager.AddClaimAsync(adminRole, new Claim(CustomClaimTypes.Permission, "projects.update"));
            //       var newAppUser = new ApplicationUser();
            //  newAppUser.UpdateUser(applicationUserViewModel);
            //  ApplicationUser newAppUser = PropertyCopy.Copy<ApplicationUser, ApplicationUserViewModel>(applicationUserViewModel);


            IActionResult actionResult = new ObjectResult(false);
            GenericResult addResult    = null;

            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            try
            {
                var userByEmail = await _userManager.FindByEmailAsync(applicationUserViewModel.Email);

                if (userByEmail != null)
                {
                    addResult = new GenericResult()
                    {
                        Succeeded = false,
                        Message   = "Email đã tồn tại"
                    };
                    actionResult = new ObjectResult(addResult);
                    return(actionResult);
                }
                var userByUserName = await _userManager.FindByNameAsync(applicationUserViewModel.UserName);

                if (userByUserName != null)
                {
                    addResult = new GenericResult()
                    {
                        Succeeded = false,
                        Message   = "Username đã tồn tại"
                    };
                    actionResult = new ObjectResult(addResult);
                    return(actionResult);
                }


                ApplicationUser newAppUser = Mapper.Map <ApplicationUserViewModel, ApplicationUser>(applicationUserViewModel);
                newAppUser.Id            = Guid.NewGuid().ToString();
                newAppUser.PARENT_ID     = null;
                newAppUser.RECORD_STATUS = "1";
                newAppUser.AUTH_STATUS   = "U";
                newAppUser.APPROVE_DT    = null;
                newAppUser.EDIT_DT       = null;
                newAppUser.PASSWORD      = null;
                newAppUser.CREATE_DT     = DateTime.Now.Date;
                newAppUser.PARENT_ID     = _userManager.GetUserId(User);

                var result = await _userManager.CreateAsync(newAppUser, applicationUserViewModel.PASSWORD);

                if (result.Succeeded)
                {
                    var listAppUserGroup = new List <ApplicationUserGroup>();
                    var groups           = applicationUserViewModel.Groups.Where(xy => xy.Check).ToList();
                    foreach (var group in groups)
                    {
                        listAppUserGroup.Add(new ApplicationUserGroup()
                        {
                            GroupId = group.ID,
                            UserId  = newAppUser.Id
                        });

                        var listRole = _appRoleService.GetListRoleByGroupId(group.ID).ToList();

                        List <string> list = new List <string>();
                        foreach (var role in listRole)
                        {
                            list.Add(role.Name);
                        }
                        foreach (var item in list)
                        {
                            await _userManager.RemoveFromRoleAsync(newAppUser, item);

                            if (!await _userManager.IsInRoleAsync(newAppUser, item))
                            {
                                IdentityResult result2 = await _userManager.AddToRoleAsync(newAppUser, item);

                                if (!result2.Succeeded)
                                {
                                    AddErrorsFromResult(result);
                                }
                            }
                        }
                    }

                    _appGroupService.AddUserToGroups(listAppUserGroup, newAppUser.Id);
                    _appGroupService.Save();


                    //DEFACEWEBSITEContext context = new DEFACEWEBSITEContext();
                    //string pass = MD5Encoder.MD5Hash(user.Password);
                    XElement xmldata = new XElement(new XElement("Root"));
                    XElement x       = new XElement("Domain", new XElement("DOMAIN", applicationUserViewModel.Domain),
                                                    new XElement("DESCRIPTION", applicationUserViewModel.DomainDesc));
                    xmldata.Add(x);

                    string command     = $"dbo.Users_Ins @p_USERNAME = '******', @p_FULLNAME= N'{newAppUser.FULLNAME}',@p_PASSWORD = '******',@p_EMAIL = '{newAppUser.Email}',@p_PHONE = {newAppUser.PHONE},@p_PARENT_ID = '',@p_DESCRIPTION = N'{newAppUser.DESCRIPTION}',@p_RECORD_STATUS = '{newAppUser.RECORD_STATUS}',@p_AUTH_STATUS = '{newAppUser.AUTH_STATUS}',@p_CREATE_DT = '{DateTime.Now.Date}',@p_APPROVE_DT = '{newAppUser.APPROVE_DT}' ,@p_EDIT_DT= '{newAppUser.EDIT_DT}' ,@p_MAKER_ID ='{newAppUser.MAKER_ID}',@p_CHECKER_ID = '{newAppUser.CHECKER_ID}',@p_EDITOR_ID = '{newAppUser.EDITOR_ID}',@DOMAIN =N'{xmldata}'";
                    var    resultStore = _context.Database.ExecuteSqlCommand(command);
                    if (resultStore == -1)
                    {
                        addResult = new GenericResult()
                        {
                            Succeeded = false,
                            Message   = "Thêm domain thất bại"
                        };
                    }

                    addResult = new GenericResult()
                    {
                        Succeeded = true,
                        Message   = "Thêm dữ liệu thành công"
                    };
                }
                else
                {
                    addResult = new GenericResult()
                    {
                        Succeeded = false,
                        Message   = "Mật khẩu đơn giản (Hãy thử lại với chữ, số, ký tự đặc biệt)"
                    };
                }
            }

            catch (Exception ex)
            {
                addResult = new GenericResult()
                {
                    Succeeded = false,
                    Message   = "Tên không được trùng"
                };
                _loggingRepository.Add(new Error()
                {
                    Message = ex.Message, StackTrace = ex.StackTrace, DateCreated = DateTime.Now
                });
                _loggingRepository.Commit();
            }


            actionResult = new ObjectResult(addResult);
            return(actionResult);
        }
コード例 #28
0
        public async Task <IActionResult> Login([FromBody] LoginViewModel model)
        {
            IActionResult _result = new ObjectResult(false);
            GenericResult _authenticationResult = null;

            try
            {
                //   var user23 = _userManager.FindByNameAsync(model.Username).Result.Claims;

                var user = await _userManager.FindByNameAsync(model.Username);

                var result = await _userManager.CheckPasswordAsync(user, model.Password);

                if (result)
                {
                    //var adminRole = await _roleManager.FindByNameAsync("Admin");
                    //if (adminRole == null)
                    //{
                    //    adminRole = new IdentityRole("Admin");
                    //    await _roleManager.CreateAsync(adminRole);
                    //}
                    //await _roleManager.AddClaimAsync(adminRole, new Claim(ClaimTypes.Role, "projects.create"));


                    //var accountManagerRole = await _roleManager.FindByNameAsync("Account Manager");

                    //if (accountManagerRole == null)
                    //{
                    //    accountManagerRole = new IdentityRole("Account Manager");
                    //    await _roleManager.CreateAsync(accountManagerRole);

                    //    await _roleManager.AddClaimAsync(accountManagerRole, new Claim(, "account.manage"));
                    //}


                    var principal = _signInManager.CreateUserPrincipalAsync(user).Result.Claims.ToList();

                    var xfd = _userManager.GetClaimsAsync(user).Result;


                    // ClaimsIdentity claim = new ClaimsIdentity();
                    // _signInManager.
                    var now    = DateTime.UtcNow;
                    var claims = new Claim[]
                    {
                        new Claim(JwtRegisteredClaimNames.Sub, model.Username),
                        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                        new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64),
                    };
                    var claimslist = claims.ToList();
                    foreach (var claim in principal)
                    {
                        claimslist.Add(claim);
                    }
                    ;

                    // Create the JWT security token and encode it.
                    var jwt = new JwtSecurityToken(
                        issuer: _jwtOptions.Issuer,
                        audience: _jwtOptions.Audience,
                        claims: principal,
                        notBefore: _jwtOptions.NotBefore,
                        expires: _jwtOptions.Expiration,
                        signingCredentials: _jwtOptions.SigningCredentials);

                    var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

                    // Serialize and return the response
                    var response = new
                    {
                        access_token = encodedJwt,
                        expires_in   = (int)_jwtOptions.ValidFor.TotalSeconds
                    };


                    if (!String.IsNullOrEmpty(model.TokenFirebase))
                    {
                        user.APPTOKEN = model.TokenFirebase;
                        await _userManager.UpdateAsync(user);
                    }

                    _authenticationResult = new GenericTokenResult()
                    {
                        Succeeded    = true,
                        Message      = "Đăng nhập thành công",
                        access_token = encodedJwt,
                        expires_in   = (int)_jwtOptions.ValidFor.TotalSeconds
                    };
                }
                else
                {
                    _authenticationResult = new GenericTokenResult()
                    {
                        Succeeded    = false,
                        Message      = "Đăng nhập thất bại vui lòng kiểm tra lại thông tin",
                        access_token = null,
                        expires_in   = 0
                    };
                }
            }
            catch (Exception ex)
            {
                _authenticationResult = new GenericResult()
                {
                    Succeeded = false,
                    Message   = ex.Message
                };

                _loggingRepository.Add(new Error()
                {
                    Message = ex.Message, StackTrace = ex.StackTrace, DateCreated = DateTime.Now
                });
                _loggingRepository.Commit();
            }

            _result = new ObjectResult(_authenticationResult);
            return(_result);
        }
        public IActionResult PostProductListPerformanceEcommerce([FromBody] Welcome welcome)
        {
            var           reports    = welcome.FormattedJson;
            var           project    = welcome.Project;
            IActionResult _result    = new ObjectResult(false);
            GenericResult _addResult = null;

            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                var version = _ProductListPerformanceEcommerceService.GetVersionFinal(project["PROJECT_ID"]);

                var rows = reports.Reports[0].Data.Rows;
                if (rows == null)
                {
                    _addResult = new GenericResult()
                    {
                        Succeeded = false,
                        Message   = "Không có dữ liệu trong 30 ngày gần nhất"
                    };
                    _result = new ObjectResult(_addResult);
                    return(_result);
                }
                for (int i = 0; i < rows.Length; i++)
                {
                    var productName = rows[i].Dimensions[0];
                    var values      = rows[i].Metrics[0].Values;

                    decimal moeny = Decimal.Parse(values[0], System.Globalization.NumberStyles.Any);
                    //  var moeny= Double.Parse(values[0], System.Globalization.NumberStyles.Float);

                    //string[] moeny = values[0].ToString().Split('E');
                    //var x = Double.Parse(moeny[0])*(10^moeny)
                    ProductListPerformanceEcommerce newProductListPerformanceEcommerce = new ProductListPerformanceEcommerce
                    {
                        PRODUCTLIST_PERFORMANCE_ECOMMERCE_ID = 0,
                        //  OVERVIEW_ECOMMERCE_ID = 0,
                        PRODUCTLIST = productName,
                        //  PRODUCT_NAME = productName,
                        //     ITEM_REVENUE = moeny.ToString(),
                        ITEM_REVENUE           = values[0],
                        PRODUCT_DETAIL_VIEWS   = values[1],
                        QUANTITY_ADDED_TO_CART = values[2],
                        QUANTITY_CHECKED_OUT   = values[3],
                        CREATE_DT     = DateTime.Now,
                        RECORD_STATUS = "1",
                        VERSION_INT   = version + 1,
                        DOMAIN        = project["DOMAIN"],
                        //       VERSION = (version + 1).ToString(),

                        PROJECT_ID = project["PROJECT_ID"]
                    };
                    _ProductListPerformanceEcommerceService.Add(newProductListPerformanceEcommerce);
                    _ProductListPerformanceEcommerceService.Save();
                }

                //ProductListPerformanceEcommerce _newProductListPerformanceEcommerce = PropertyCopy.Copy<ProductListPerformanceEcommerce, DomainViewModel>(ProductListPerformanceEcommerce);


                //_newProductListPerformanceEcommerce.CREATE_DT = DateTime.Now;
                //_newProductListPerformanceEcommerce.PROJECT_ID = 1;



                _addResult = new GenericResult()
                {
                    Succeeded = true,
                    Message   = "Add success."
                };
            }
            catch (Exception ex)
            {
                _addResult = new GenericResult()
                {
                    Succeeded = false,
                    Message   = ex.Message
                };

                _loggingRepository.Add(new Error()
                {
                    Message = ex.Message, StackTrace = ex.StackTrace, DateCreated = DateTime.Now
                });
                _loggingRepository.Commit();
            }

            _result = new ObjectResult(_addResult);
            return(_result);
        }
コード例 #30
0
        public async Task <IActionResult> Get(int?page, int?pageSize)
        {
            PaginationSet <WalkViewModel> pagedSet = new PaginationSet <WalkViewModel>();

            try
            {
                //if (_signInManager.IsSignedIn(User))
                if (true)
                {
                    int currentPage     = page.Value;
                    int currentPageSize = pageSize.Value;

                    List <Walk> _walks      = null;
                    int         _totalWalks = new int();

                    //if (await _authorizationService.AuthorizeAsync(User, "AdminOnly"))
                    if (true)
                    {
                        _walks = _walkRepository
                                 .AllIncluding(w => w.WalkSights)
                                 .OrderBy(w => w.Id)
                                 .Skip(currentPage * currentPageSize)
                                 .Take(currentPageSize)
                                 .ToList();

                        _totalWalks = _walkRepository.GetAll().Count();
                    }
                    else
                    {
                        _walks = _walkRepository
                                 .FindBy(w => w.UserId == _userManager.GetUserId(User))
                                 .OrderBy(w => w.Id)
                                 .Skip(currentPage * currentPageSize)
                                 .Take(currentPageSize)
                                 .ToList();

                        _totalWalks = _walks.Count();
                    }

                    IEnumerable <WalkViewModel> _walksVM = Mapper.Map <IEnumerable <Walk>, IEnumerable <WalkViewModel> >(_walks);

                    pagedSet = new PaginationSet <WalkViewModel>()
                    {
                        Page       = currentPage,
                        TotalCount = _totalWalks,
                        TotalPages = (int)Math.Ceiling((decimal)_totalWalks / currentPageSize),
                        Items      = _walksVM
                    };
                }
                else
                {
                    CodeResultStatus _codeResult = new CodeResultStatus(401);
                    return(new ObjectResult(_codeResult));
                }
            }
            catch (Exception ex)
            {
                _loggingRepository.Add(new Error()
                {
                    Message = ex.Message, StackTrace = ex.StackTrace, CreatedDate = DateTime.Now
                });
                _loggingRepository.Commit();
            }

            return(new ObjectResult(pagedSet));
        }