Ejemplo n.º 1
0
        public async Task <IActionResult> ConfirmPhoneVerify(string phoneNumber, string code)
        {
            try
            {
                _log.LogInformation("CONFIRM PHONE VERIFY - START");
                if (string.IsNullOrEmpty(code))
                {
                    _log.LogInformation($"PHONE VERIFY CODE USER INPUT INVALID. USER INPUT: {code}");
                    ViewBag.VerifyError = ConstantsError.ERROR_PHONE_VERIFY_INVALID;
                    return(new OkObjectResult(ApiResponseModel.GetFailureModel(ConstantsError.ERROR_PHONE_VERIFY_INVALID)));
                }

#if DEBUG
                var user = _userManager.FindByNameAsync("admin").Result;
#else
                var user = await _userManager.GetUserAsync(HttpContext.User).Result;
#endif
                var verifyCode = user.PhoneOTP;

                if (string.IsNullOrEmpty(verifyCode) || code != verifyCode || string.IsNullOrEmpty(phoneNumber) || user.PhoneNumber != phoneNumber)
                {
                    _log.LogInformation($"PHONE VERIFY CODE USER INPUT INVALID. USER INPUT: {code}");
                    ViewBag.VerifyError = ConstantsError.ERROR_PHONE_VERIFY_INVALID;
                    return(new OkObjectResult(ApiResponseModel.GetFailureModel(ConstantsError.ERROR_PHONE_VERIFY_INVALID)));
                }

                if (user.OTPTime.AddMinutes(AppConfigConstants.USER_PHONE_VERIFY_TIMEOUT) < DateTime.Now)
                {
                    //OTP hết hạn
                    ViewBag.VerifyError = ConstantsError.ERROR_PHONE_VERIFY_TIMEOUT;
                    return(new OkObjectResult(ApiResponseModel.GetFailureModel(ConstantsError.ERROR_PHONE_VERIFY_TIMEOUT)));
                }

                if (code == verifyCode)
                {
                    _log.LogInformation("VERIFY CODE VALID. UPDATING USER INFO");
                    //Mã xác nhận đúng=> Thực hiện lưu sđt và cập nhật trạng thái số điện thoại đã xác nhận vào database
                    user.PhoneOTP             = string.Empty;
                    user.PhoneNumberConfirmed = true;

                    //Cập nhật thông tin User
                    await _userManager.UpdateAsync(user);

                    _log.LogInformation("CONFIRM PHONE VERIFY - SUCCESS");
                    _log.LogInformation("CONFIRM PHONE VERIFY - END");
                    return(new OkObjectResult(ApiResponseModel.GetSuccessModel("Phone confirm success")));
                }
                else
                {
                    _log.LogInformation($"PHONE VERIFY CODE USER INPUT INVALID. USER INPUT: {code}");
                    ViewBag.VerifyError = ConstantsError.ERROR_PHONE_VERIFY_INVALID;
                    _log.LogInformation("CONFIRM PHONE VERIFY - END");
                    return(new OkObjectResult(ApiResponseModel.GetFailureModel(ConstantsError.ERROR_PHONE_VERIFY_INVALID)));
                }
            }
            catch (Exception ex)
            {
                _log.LogInformation($"CONFIRM PHONE VERIFY ERROR. - {ex.ToString()}");
                return(new OkObjectResult(ApiResponseModel.GetErrorModel(ConstantsError.ERROR_PHONE_VERIFY_ERROR)));
            }
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> UploadImage(List <IFormFile> files)
        {
            try
            {
                _log.LogInformation("UPLOAD DATA - START");
                DateTime now = DateTime.Now;
                if (files.Count == 0)
                {
                    _log.LogWarning("FILE IS EMPTY");
                    return(new OkObjectResult(ApiResponseModel.GetFailureModel("File is empty")));
                }
                else
                {
#if !DEBUG
                    if (!User.Identity.IsAuthenticated)
                    {
                        _log.LogWarning("USER NOT LOGIN");
                        return(new OkObjectResult(ApiResponseModel.GetFailureModel(ConstantsError.ERROR_USER_IS_NOT_LOGIN)));
                    }
#endif
                    var file     = files[0];
                    var fileName = file.GetFilename().Trim('"');

                    var imageFolder = $@"\images\{now.ToString("yyyyMMdd")}\{Guid.NewGuid().ToString()}";

                    string folder = _hostingEnvironment.WebRootPath + imageFolder;

                    if (!Directory.Exists(folder))
                    {
                        Directory.CreateDirectory(folder);
                    }
                    string filePath = Path.Combine(folder, fileName);

                    _log.LogInformation($"FILE PATH TO SAVE: {filePath}");
                    using (FileStream fs = System.IO.File.Create(filePath))
                    {
                        await file.CopyToAsync(fs);

                        fs.Flush();
                    }
                    _log.LogInformation("UPLOAD DATA SUCCESS. SAVE TO DB");

                    string urlImage = Path.Combine(imageFolder, fileName);
#if DEBUG
                    var userId = _userManager.FindByNameAsync("admin").Result.Id;
#else
                    var userId = User.GetSpecificClaim("UserId");
#endif

                    //Update AuthenticateImage and Status
                    if (!_appUserService.UpdateUrlImage(userId, urlImage))
                    {
                        _log.LogInformation("CAN NOT SAVE URL IMAGE TO DB.");
                        return(new OkObjectResult(ApiResponseModel.GetFailureModel("Save data error.")));
                    }

                    _log.LogInformation("UPLOAD DATA - END");

                    return(new OkObjectResult(ApiResponseModel.GetSuccessModel(urlImage.Replace(@"\", @"/"))));
                }
            }
            catch (Exception ex)
            {
                _log.LogError($"UPLOAD DATA ERROR. \n {ex.ToString()}");
                return(new OkObjectResult(ApiResponseModel.GetErrorModel("Upload file error. Please try again!")));
            }
        }
        public HttpResponseMessage FindContractors(ContractorRequestModel model)
        {
            try
            {
                //if (model == null)
                //{
                //    var response = new ApiResponseModel
                //    {
                //        Data = null,
                //        Message = "Mandatory  are null.",
                //        Success = false
                //    };
                //    return Request.CreateResponse(HttpStatusCode.InternalServerError, response);
                //}

                var contractors = AdminService.GetUsersByType("Contractor");
                if (model.CategoryId != 0)
                {
                    contractors = contractors.Where(con => con.CategoryId == model.CategoryId).ToList();
                }
                var filteredCons = new List <AdminModels.LocalUser>(contractors);
                if (!string.IsNullOrEmpty(model.LocationCords) && model.LocationCords != "" && !string.IsNullOrEmpty(model.Distance))
                {
                    var latlng = model.LocationCords.Split('_');
                    if (latlng.Length == 2)
                    {
                        var userLoc = Commons.Commons.ConvertLatLonToDbGeography(latlng[1], latlng[0]);
                        if (userLoc != null && userLoc.Latitude != null && userLoc.Longitude != null)
                        {
                            filteredCons = new List <LocalUser>();
                            foreach (var con in contractors)
                            {
                                var dist = Commons.GeodesicDistance.GetDistance((double)userLoc.Latitude, (double)userLoc.Longitude, Convert.ToDouble(con.lat), Convert.ToDouble(con.lng));
                                if (dist != null && (int)dist < Convert.ToInt16(model.Distance))
                                {
                                    con.DistanceFromOrigin = (double)dist;
                                    filteredCons.Add(con);
                                }
                            }
                        }
                    }
                }
                string baseUrl = HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority +
                                 HttpContext.Current.Request.ApplicationPath.TrimEnd('/');


                filteredCons = filteredCons.OrderBy(fil => fil.DistanceFromOrigin).ToList();
                var places  = Commons.Commons.FormatMapData(filteredCons, baseUrl);
                var allJobs = new MapPlaceWrapper
                {
                    status  = "found",
                    listing = places,
                };
                return(Request.CreateResponse(HttpStatusCode.OK, new ApiResponseModel
                {
                    Success = true,
                    Message = "Successfully fetched Contractors",
                    Data = allJobs
                }));
            }
            catch (Exception excep)
            {
                var response = new ApiResponseModel
                {
                    Data    = null,
                    Message = excep.InnerException.Message,
                    Success = false
                };
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, response));
            }
        }
Ejemplo n.º 4
0
        public async Task <IActionResult> PhoneVerify(string phoneNumber)
        {
            try
            {
                _log.LogInformation("PHONE VERIFY - START");
                if (string.IsNullOrEmpty(phoneNumber))
                {
                    return(new OkObjectResult(ApiResponseModel.GetFailureModel(ConstantsError.ERROR_PHONE_INVALID)));
                }
#if !DEBUG
                //Kiểm tra user đã đăng nhập hay chưa
                if (!User.Identity.IsAuthenticated)
                {
                    return(new OkObjectResult(ApiResponseModel.GetFailureModel(ConstantsError.ERROR_USER_IS_NOT_LOGIN)));
                }
#endif
                //Lấy thông tin user đang đăng nhập
                _log.LogInformation("GET USER INFOMATION");

#if DEBUG
                var user = _userManager.FindByNameAsync("admin").Result;
#else
                var user = await _userManager.GetUserAsync(HttpContext.User).Result;
#endif
                if (!user.PhoneNumberConfirmed)
                {
                    //Tạo 1 code để gửi User verify
                    string verifyCode = new Random().Next(100000, 999999).ToString();
#if DEBUG
                    verifyCode = "999999";
#endif
                    //Build nội dung tin nhắn gửi cho User
                    string content = string.Format(AppConfigConstants.USER_VEIRFY_PHONE_CONTENT, verifyCode);

                    //Gửi tin nhắn mã số xác nhận sđt cho user
                    _log.LogInformation($"BEGIN SEND SMS TO USER. PHONE NUMBER IS: {phoneNumber}");
                    if (_smsHelper.SendSms(phoneNumber, content))
                    {
                        //_cache.Set<string>(phoneNumber, verifyCode, TimeSpan.FromMinutes(15));
                        user.PhoneNumber = phoneNumber;
                        user.PhoneOTP    = verifyCode;
                        user.OTPTime     = DateTime.Now;

                        //Cập nhật số OTP hiện tại
                        await _userManager.UpdateAsync(user);

                        ViewBag.PhoneNumber = phoneNumber;
                        _log.LogInformation("SEND VERIFY CODE AND SAVE VERIFY CODE AND PHONE NUMBER SUCCESS. - END");
                        return(new OkObjectResult(ApiResponseModel.GetSuccessModel("Success")));
                    }
                    else
                    {
                        return(new OkObjectResult(ApiResponseModel.GetFailureModel(ConstantsError.ERROR_PHONE_VERIFY_CANNOTSEND)));
                    }
                }
                else
                {
                    return(new OkObjectResult(ApiResponseModel.GetFailureModel(ConstantsError.ERROR_NOT_FOUND)));
                }
            }
            catch (Exception ex)
            {
                _log.LogInformation($"SEND SMS TO VERIFY PHONE ERROR. \n {ex.ToString()}");
                return(new OkObjectResult(ApiResponseModel.GetErrorModel(ConstantsError.ERROR_PHONE_VERIFY_ERROR)));
            }
        }
Ejemplo n.º 5
0
        public async Task <HttpResponseMessage> RegisterUser(RegisterViewModel model)
        {
            try
            {
                #region Validation
                HttpResponseMessage endResponse;
                var response = new ApiResponseModel {
                    Data = model
                };
                if (model == null || !ModelState.IsValid)
                {
                    response.Message = "Mandatory data is missing. ";
                    foreach (var error in ModelState)
                    {
                        response.Message = response.Message + "\n" + error.Key;
                    }
                    response.Success = false;
                    endResponse      = Request.CreateResponse(HttpStatusCode.BadRequest, response);
                    return(endResponse);
                }
                if (model.Type == "Contractor" && string.IsNullOrEmpty(model.CNIC))
                {
                    response.Message = "CNIC is missing. ";
                    response.Success = false;
                    endResponse      = Request.CreateResponse(HttpStatusCode.BadRequest, response);
                    return(endResponse);
                }
                if (model.Type == "Contractor" && model.CategoryId == 0)
                {
                    response.Message = "Category is missing for contractor ";
                    response.Success = false;
                    endResponse      = Request.CreateResponse(HttpStatusCode.BadRequest, response);
                    return(endResponse);
                }
                if (model.LocationCord == null || string.IsNullOrEmpty(model.LocationName))
                {
                    response.Message = "LocationCord(lat_lng)/LocationName is missing ";
                    response.Success = false;
                    endResponse      = Request.CreateResponse(HttpStatusCode.BadRequest, response);
                    return(endResponse);
                }
                #endregion
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var usermanager = Request.GetOwinContext().GetUserManager <ApplicationUserManager>();
                var result      = await usermanager.CreateAsync(user, model.Password);

                var isUserCreated = result.Succeeded;
                if (isUserCreated)
                {
                    try
                    {
                        response.Message = model.FullName + " has been registered";
                        response.Success = true;
                        UserServices.AddUserProperties(model, user.Id);
                        var baseUrlforimg = System.Web.Hosting.HostingEnvironment.MapPath("/Images/Profiles/");
                        UserServices.CreateUserAvatar(baseUrlforimg + user.Id);
                        response.Data = user;

                        var content = "Hi " + model.FullName +
                                      "!\nYou have been successfully registered as a " + model.Type +
                                      " at KamSham.Pk.";
                        if (model.Type == "Contractor")
                        {
                            content = content + "You will be able to login once we approve your account information.";
                        }
                        content = content + "\n-KamSham Team\n+923084449991";
                        KaamShaam.Services.EmailService.SendEmail(user.Email, "Registration Notification | KamSham.Pk", content);
                    }
                    catch (Exception excep)
                    {
                        var foundUser    = usermanager.FindById(user.Id);
                        var responseMesg = await usermanager.DeleteAsync(user);

                        if (responseMesg.Succeeded)
                        {
                            // user is deleted
                        }
                        response.Message = "Data is missing." + excep.InnerException.Message;
                        response.Success = false;
                    }
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        response.Message = response.Message + "\n" + error;
                    }
                    response.Success = false;
                }
                endResponse = Request.CreateResponse(HttpStatusCode.OK, response);
                return(endResponse);
            }
            catch (Exception excep)
            {
                var response = new ApiResponseModel
                {
                    Data    = model,
                    Message = excep.InnerException.Message,
                    Success = false
                };
                var endResponse = Request.CreateResponse(HttpStatusCode.InternalServerError, response);
                return(endResponse);
            }
        }
Ejemplo n.º 6
0
        public void OnActionExecuting(ActionExecutingContext context)
        {
            var response    = new ApiResponseModel();
            var validations = new List <Validation>();
            var AuthToken   = (context.HttpContext.Request.Headers.TryGetValue("AuthToken", out var authorizationToken)) ? authorizationToken.ToString() : string.Empty;
            var ip          = context.HttpContext.Connection.RemoteIpAddress;

            try
            {
                if (string.IsNullOrEmpty(AuthToken))
                {
                    validations.Add(new Validation()
                    {
                        Key = "Token", Value = "Please send your Token to Access this resource"
                    });
                }
                else
                {
                    var val = AuthToken.Split(".");

                    if (val.Length != int.Parse(_uow.GetAppSettings("TokenLength")))
                    {
                        validations.Add(new Validation()
                        {
                            Key = "Token", Value = "Incorrect Token Format"
                        });
                    }
                    else
                    {
                        var UserToken    = Helper.Decrypt(val[0], _uow.GetAppSettings("passPhrase"), _uow.GetAppSettings("SaltFixed"), _uow.GetAppSettings("hashAlgorithm"), int.Parse(_uow.GetAppSettings("passwordIterations")), _uow.GetAppSettings("initVector"), int.Parse(_uow.GetAppSettings("keySize")));
                        var IpAddress    = Helper.Decrypt(val[1], _uow.GetAppSettings("passPhrase"), _uow.GetAppSettings("SaltFixed"), _uow.GetAppSettings("hashAlgorithm"), int.Parse(_uow.GetAppSettings("passwordIterations")), _uow.GetAppSettings("initVector"), int.Parse(_uow.GetAppSettings("keySize")));;
                        var ExecutedDate = Helper.Decrypt(val[2], _uow.GetAppSettings("passPhrase"), _uow.GetAppSettings("SaltFixed"), _uow.GetAppSettings("hashAlgorithm"), int.Parse(_uow.GetAppSettings("passwordIterations")), _uow.GetAppSettings("initVector"), int.Parse(_uow.GetAppSettings("keySize")));;

                        //Full Token : MsJPOXWboRbZL0Z14auT8w==.X3M3Yl3MucZr+LXqJpS2aA==.7GgDQjrzTdLDVkw/2q6U3xYt3Kk7pKtWp1WHyMHhE3s=

                        //MsJPOXWboRbZL0Z14auT8w== --> Encrypt Tante Erni
                        if (UserToken != "tanteerni")
                        {
                            validations.Add(new Validation()
                            {
                                Key = "Token", Value = "Incorrect Token Value"
                            });
                        }

                        //X3M3Yl3MucZr+LXqJpS2aA== --> ::1 (Localhost)
                        if (IpAddress != ip.ToString())
                        {
                            validations.Add(new Validation()
                            {
                                Key = "IpAddress", Value = "Different IP detected"
                            });
                        }

                        //7GgDQjrzTdLDVkw/2q6U3xYt3Kk7pKtWp1WHyMHhE3s= --> 2020-05-22 13:35:53
                        var date = DateTime.Parse(ExecutedDate);
                        //if(date )
                    }
                }

                response.Validations = validations;

                if (response.Validations.Count > 0)
                {
                    context.HttpContext.Response.StatusCode = (int)ResponseMessageEnum.UnAuthorized;
                    context.Result = ApiHelper.Response(ResponseMessageEnum.UnAuthorized, response);
                }
            }
            catch
            {
                context.Result = ApiHelper.Response(ResponseMessageEnum.InternalServerError, response);
            }
        }
Ejemplo n.º 7
0
        public static IEnumerable <Tuple <IResponseAction, ResponseActionState> > GetActions(ApiResponseModel model)
        {
            var contentType = model.ContentType;

            if (contentType != null)
            {
                contentType = contentType.Split(';').First();

                List <Type> list;
                if (actionsByContentType.TryGetValue(contentType, out list))
                {
                    foreach (var type in list)
                    {
                        var action = (IResponseAction)Activator.CreateInstance(type);
                        yield return(Tuple.Create(action, ResponseActionState.Enabled));
                    }
                }
            }
            foreach (var item in actionsWithPredicate)
            {
                var responseActionState = item.Item1(model);
                var action = (IResponseAction)Activator.CreateInstance(item.Item2);
                yield return(Tuple.Create(action, responseActionState));
            }
        }
        public ApiResponseModel <Data.Entity.Broadcast> EditBroadcastWithDetail(int id, [FromBody] AddRequestModel requestModel, [FromHeader] string displayLanguage)
        {
            var responseModel = new ApiResponseModel <Data.Entity.Broadcast>()
            {
                DisplayLanguage = displayLanguage
            };
            //user bilgilerinden filitre parametreleri eklenir.
            TokenModel tokenModel = TokenHelper.DecodeTokenFromRequestHeader(Request);
            var        employeeId = tokenModel.ID;

            try
            {
                var broadcast = _broadcastService.GetById(id);
                if (broadcast == null)
                {
                    responseModel.ResultStatusCode    = ResultStatusCodeStatic.Error;
                    responseModel.ResultStatusMessage = "No Records Found";
                    return(responseModel);
                }

                var record = new Data.Entity.Broadcast();
                broadcast.Id            = requestModel.Id;
                broadcast.TitleTR       = requestModel.TitleTR;
                broadcast.TitleEN       = requestModel.TitleEN;
                broadcast.DescriptionTR = requestModel.DescriptionTR;
                broadcast.DescriptionEN = requestModel.DescriptionEN;
                if (!String.IsNullOrEmpty(requestModel.ImageFilePath))
                {
                    broadcast.ImageFilePath = "BroadcastFiles/" + requestModel.ImageFilePath;
                }
                else
                {
                    broadcast.ImageFilePath = broadcast.ImageFilePath;
                }
                broadcast.VideoFileUrl          = requestModel.VideoFileUrl;
                broadcast.ValidationEndDateTime = requestModel.ValidationEndDateTime;
                broadcast.ModifiedDateTime      = DateTime.Now;
                broadcast.ModifiedBy            = employeeId;

                var dbResult = _broadcastService.Update(broadcast);
                if (dbResult > 0)
                {
                    responseModel.Data                = record; // oluşturulan entity bilgisinde id kolonu atanmış olur ve entity geri gönderiliyor
                    responseModel.ResultStatusCode    = ResultStatusCodeStatic.Success;
                    responseModel.ResultStatusMessage = "Success";
                }
                else
                {
                    //hata oluşursa varsa  resmi silmemiz gerekecek
                    if (!string.IsNullOrEmpty(requestModel.ImageFilePath))
                    {
                        var filePath = Path.Combine(_hostingEnvironment.WebRootPath, "BroadcastFiles") + "\\" + requestModel.ImageFilePath;
                        if (System.IO.File.Exists(filePath))
                        {
                            System.IO.File.Delete(filePath);
                        }
                    }
                    responseModel.ResultStatusCode    = ResultStatusCodeStatic.Error;
                    responseModel.ResultStatusMessage = "Could Not Be Saved";
                }
            }
            catch (Exception ex)
            {
                //hata oluşursa varsa  resmi silmemiz gerekecek
                if (!string.IsNullOrEmpty(requestModel.ImageFilePath))
                {
                    var filePath = Path.Combine(_hostingEnvironment.WebRootPath, "BroadcastFiles") + "\\" + requestModel.ImageFilePath;
                    if (System.IO.File.Exists(filePath))
                    {
                        System.IO.File.Delete(filePath);
                    }
                }
                responseModel.ResultStatusCode    = ResultStatusCodeStatic.Error;
                responseModel.ResultStatusMessage = ex.Message;
            }
            return(responseModel);
        }
Ejemplo n.º 9
0
        public ApiResponseModel <Broadcast.Web.Business.Models.Broadcast.Broadcast> AddWithDetail(string userToken, string displayLanguage, AddBroadcastWithDetail addbroadcast)
        {
            ApiResponseModel <Broadcast.Web.Business.Models.Broadcast.Broadcast> result = new ApiResponseModel <Broadcast.Web.Business.Models.Broadcast.Broadcast>();

            // ilk olarak image varsa o kayıt edilir.
            ApiResponseModel <string> resultImageAdd = new ApiResponseModel <string>();

            if (addbroadcast.ImageInformation != null && addbroadcast.ImageInformation.Length > 0)
            {
                using (HttpClient httpClient = new HttpClient())
                {
                    httpClient.BaseAddress = new Uri(ConfigHelper.ApiUrl);
                    httpClient.DefaultRequestHeaders.Accept.Clear();
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", userToken);
                    httpClient.DefaultRequestHeaders.Add("DisplayLanguage", displayLanguage);

                    HttpResponseMessage response = httpClient.PostAsImageFiles(string.Format("v1/Broadcasts/upload-file"), addbroadcast.ImageInformation).Result;
                    resultImageAdd = response.Content.ReadAsJsonAsync <ApiResponseModel <string> >().Result;
                    if (resultImageAdd.ResultStatusCode != ResultStatusCodeStatic.Success)
                    {
                        result.ResultStatusCode    = resultImageAdd.ResultStatusCode;
                        result.ResultStatusMessage = resultImageAdd.ResultStatusMessage;
                        return(result);
                    }
                }
            }

            //sonrasında veriler kayıt edilir.
            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.BaseAddress = new Uri(ConfigHelper.ApiUrl);
                httpClient.DefaultRequestHeaders.Accept.Clear();
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", userToken);
                httpClient.DefaultRequestHeaders.Add("DisplayLanguage", displayLanguage);

                var portalApiRequestModel = new AddRequestModel();
                portalApiRequestModel.TitleTR         = addbroadcast.TitleTR;
                portalApiRequestModel.TitleEN         = addbroadcast.TitleEN;
                portalApiRequestModel.DescriptionTR   = addbroadcast.DescriptionTR;
                portalApiRequestModel.DescriptionEN   = addbroadcast.DescriptionEN;
                portalApiRequestModel.BroadcastTypeId = addbroadcast.BroadcastTypeId;
                portalApiRequestModel.BroadcastTypeId = addbroadcast.BroadcastTypeId;
                portalApiRequestModel.BroadcastTypeId = addbroadcast.BroadcastTypeId;
                portalApiRequestModel.BroadcastTypeId = addbroadcast.BroadcastTypeId;
                if (addbroadcast.ImageInformation != null && addbroadcast.ImageInformation.Length > 0)
                {
                    portalApiRequestModel.ImageFilePath = resultImageAdd.Data;
                }
                portalApiRequestModel.VideoFileUrl          = addbroadcast.VideoFileUrl;
                portalApiRequestModel.ValidationEndDateTime = addbroadcast.ValidationEndDateTime;
                portalApiRequestModel.IsActive        = false;
                portalApiRequestModel.CreatedBy       = SessionHelper.CurrentUser.ID;
                portalApiRequestModel.BroadcastTypeId = addbroadcast.BroadcastTypeId;

                HttpResponseMessage response = httpClient.PostAsJsonAsync(string.Format("v1/Broadcasts"), portalApiRequestModel).Result;
                result = response.Content.ReadAsJsonAsync <ApiResponseModel <Broadcast.Web.Business.Models.Broadcast.Broadcast> >().Result;
            }

            return(result);
        }
Ejemplo n.º 10
0
        public void OnActionExecuting(ActionExecutingContext context)
        {
            var response       = new ApiResponseModel();
            var validations    = new List <Validation>();
            var AuthToken      = (context.HttpContext.Request.Headers.TryGetValue("AuthToken", out var authorizationToken)) ? authorizationToken.ToString() : string.Empty;
            var ip             = context.HttpContext.Connection.RemoteIpAddress;
            var auditLoginRepo = new AuditLoginRepository(_uow);
            var currentData    = new AuditLogin();

            try
            {
                if (string.IsNullOrEmpty(AuthToken))
                {
                    validations.Add(new Validation()
                    {
                        Key = "Token", Value = "Please send your Token to Access this resource"
                    });
                }
                else
                {
                    var val = AuthToken.Split(".");

                    if (val.Length != int.Parse(_uow.GetAppSettings("SecuredTokenLength")))
                    {
                        validations.Add(new Validation()
                        {
                            Key = "Token", Value = "Incorrect Token Format"
                        });
                    }
                    else
                    {
                        var UserClaim    = Helper.Decrypt(val[0], _uow.GetAppSettings("passPhrase"), _uow.GetAppSettings("SaltFixed"), _uow.GetAppSettings("hashAlgorithm"), int.Parse(_uow.GetAppSettings("passwordIterations")), _uow.GetAppSettings("initVector"), int.Parse(_uow.GetAppSettings("keySize")));
                        var UserToken    = Helper.Decrypt(val[1], _uow.GetAppSettings("passPhrase"), _uow.GetAppSettings("SaltFixed"), _uow.GetAppSettings("hashAlgorithm"), int.Parse(_uow.GetAppSettings("passwordIterations")), _uow.GetAppSettings("initVector"), int.Parse(_uow.GetAppSettings("keySize")));
                        var IpAddress    = Helper.Decrypt(val[2], _uow.GetAppSettings("passPhrase"), _uow.GetAppSettings("SaltFixed"), _uow.GetAppSettings("hashAlgorithm"), int.Parse(_uow.GetAppSettings("passwordIterations")), _uow.GetAppSettings("initVector"), int.Parse(_uow.GetAppSettings("keySize")));;
                        var ExecutedDate = Helper.Decrypt(val[3], _uow.GetAppSettings("passPhrase"), _uow.GetAppSettings("SaltFixed"), _uow.GetAppSettings("hashAlgorithm"), int.Parse(_uow.GetAppSettings("passwordIterations")), _uow.GetAppSettings("initVector"), int.Parse(_uow.GetAppSettings("keySize")));;

                        UserClaim UserClaimResult = Helper.JSONDeserialize <UserClaim>(UserClaim);

                        _uow.OpenConnection("dbConnection");

                        currentData = auditLoginRepo.ReadByLambda(x => x.UserID == UserClaimResult.UserID).FirstOrDefault();

                        if (currentData == null)
                        {
                            validations.Add(new Validation()
                            {
                                Key = "User", Value = "We couldnt find your user id"
                            });
                        }
                        else
                        {
                            if (currentData.UserKey != UserToken)
                            {
                                validations.Add(new Validation()
                                {
                                    Key = "User", Value = "Incorrect User Token"
                                });
                            }
                            else
                            {
                                if (currentData.IPAddress != IpAddress)
                                {
                                    validations.Add(new Validation()
                                    {
                                        Key = "User", Value = "Oooppsss another user use your user id"
                                    });
                                }
                                else
                                {
                                    if (currentData.IPAddress != ip.ToString())
                                    {
                                        validations.Add(new Validation()
                                        {
                                            Key = "User", Value = "Oooppsss there is someone on middle"
                                        });
                                    }
                                    else
                                    {
                                        ////7GgDQjrzTdLDVkw/2q6U3xYt3Kk7pKtWp1WHyMHhE3s= --> 2020-05-22 13:35:53
                                        var date = DateTime.Parse(ExecutedDate);
                                    }
                                }
                            }
                        }
                    }
                }

                response.Validations = validations;

                if (response.Validations.Count > 0)
                {
                    context.HttpContext.Response.StatusCode = (int)ResponseMessageEnum.UnAuthorized;
                    context.Result = ApiHelper.Response(ResponseMessageEnum.UnAuthorized, response);
                }
            }
            catch
            {
                context.Result = ApiHelper.Response(ResponseMessageEnum.InternalServerError, response);
            }
        }
Ejemplo n.º 11
0
        protected static ApiInputModel GetOffsetInput(ApiResponseModel response)
        {
            var offsetInput = response.Api.Inputs.SingleOrDefault(x => x.Name == "offset");

            return(offsetInput);
        }
 protected async Task <IActionResult> GenericResponse(ApiResponseModel response)
 {
     return(await GenericResponse(response.Status, response.Message, response.Data));
 }
Ejemplo n.º 13
0
        public ApiResponseModel Login(MasterUser data, string ipAddress)
        {
            var response    = new ApiResponseModel();
            var validations = new List <Validation>();

            _uow.OpenConnection(base.SQLDBConn);

            var SaltFixed          = _uow.GetAppSettings("SaltFixed");
            var passPhrase         = _uow.GetAppSettings("passPhrase");
            var hashAlgorithm      = _uow.GetAppSettings("hashAlgorithm");
            var passwordIterations = _uow.GetAppSettings("passwordIterations");
            var initVector         = _uow.GetAppSettings("initVector");
            var keySize            = _uow.GetAppSettings("keySize");

            MasterUser currentData     = new MasterUser();
            var        UserRepository  = new MasterUserRepository(_uow);
            var        dataAudit       = new AuditLogin();
            var        AuthToken       = string.Empty;
            var        UserKey         = string.Empty;
            var        Ip              = string.Empty;
            var        UserClaimResult = string.Empty;

            try
            {
                currentData = UserRepository.GetSingleData(data);

                if (currentData == null)
                {
                    validations.Add(new Validation()
                    {
                        Key = "Username", Value = "We could not find your username, make sure you input the right username"
                    });
                }
                else
                {
                    data.Password = Helper.HashWithSalt(data.Password, currentData.PasswordSalt, SHA384.Create());

                    if (data.Password != currentData.Password)
                    {
                        validations.Add(new Validation()
                        {
                            Key = "Password", Value = "Password is incorrect"
                        });
                    }
                    else
                    {
                        dataAudit.UserID    = currentData.UserID;
                        dataAudit.IPAddress = ipAddress;
                        AuditLogin(ref dataAudit);

                        var userClaim = GetUserClaim(data);

                        var obj = new UserClaim
                        {
                            UserID       = dataAudit.UserID,
                            UserEmail    = userClaim.Email,
                            UserName     = userClaim.UserName,
                            UserFullName = userClaim.FullName
                        };

                        UserClaimResult = Helper.Encrypt(Helper.JSONSerialize(obj), passPhrase, SaltFixed, hashAlgorithm, int.Parse(passwordIterations), initVector, int.Parse(keySize));
                        UserKey         = Helper.Encrypt(dataAudit.UserKey, passPhrase, SaltFixed, hashAlgorithm, int.Parse(passwordIterations), initVector, int.Parse(keySize));
                        Ip = Helper.Encrypt(ipAddress, passPhrase, SaltFixed, hashAlgorithm, int.Parse(passwordIterations), initVector, int.Parse(keySize));

                        AuthToken = UserClaimResult + "." + UserKey + "." + Ip;

                        response.Result = new { AuthToken = AuthToken };
                    }
                }

                response.Validations = validations;
                return(response);
            }
            catch
            {
                throw;
            }
            finally
            {
                _uow.Dispose();
            }
        }
Ejemplo n.º 14
0
 protected BaseCommandHandler()
 {
     ApiResponse = new ApiResponseModel();
 }
Ejemplo n.º 15
0
        public async Task <HttpResponseMessage> LoginUser(LoginViewModel model)
        {
            try
            {
                HttpResponseMessage endResponse;
                var response = new ApiResponseModel {
                    Data = model
                };
                if (model == null || string.IsNullOrEmpty(model.Password) || string.IsNullOrEmpty(model.Email))
                {
                    response.Success = false;
                    response.Message = "Mandatory data fields are missing/not mapped or not in right format";
                    endResponse      = Request.CreateResponse(HttpStatusCode.BadRequest, response);
                    return(endResponse);
                }
                var isApproved = UserAdminService.IsUserApproved(model.Email);
                if (!isApproved)
                {
                    response.Message = "Account is not approved by Admin.";
                    response.Success = false;

                    #region Check credential of unapproved user
                    var signInManager = HttpContext.Current.GetOwinContext().Get <ApplicationSignInManager>();
                    var result        =
                        await
                        signInManager.PasswordSignInAsync(model.Email, model.Password,
                                                          true,
                                                          shouldLockout : false);

                    switch (result)
                    {
                    case SignInStatus.Failure:
                    {
                        response.Message = "Invalid Username/Password.";
                        break;
                    }
                    }
                    #endregion
                }
                else
                {
                    var signInManager = HttpContext.Current.GetOwinContext().Get <ApplicationSignInManager>();
                    var result        =
                        await
                        signInManager.PasswordSignInAsync(model.Email, model.Password,
                                                          true,
                                                          shouldLockout : false);

                    switch (result)
                    {
                    case SignInStatus.Success:
                    {
                        var usermanager = Request.GetOwinContext().GetUserManager <ApplicationUserManager>();
                        var uid         = usermanager.FindByEmail(model.Email).Id;
                        response.Message = "Logged-in successfully";
                        response.Success = true;
                        response.JToken  = "a%&@JK*@#CG|wJ";
                        response.UserId  = uid;
                        break;
                    }

                    default:     /* Optional */
                    {
                        response.Message = "Invalid Username/Password.";
                        response.Success = false;
                        response.JToken  = null;
                        break;
                    }
                    }
                }
                endResponse = Request.CreateResponse(HttpStatusCode.OK, response);
                return(endResponse);
            }
            catch (Exception excep)
            {
                var response = new ApiResponseModel
                {
                    Data    = model,
                    Message = excep.InnerException.Message,
                    Success = false
                };
                var endResponse = Request.CreateResponse(HttpStatusCode.InternalServerError, response);
                return(endResponse);
            }
        }
Ejemplo n.º 16
0
        //public static async void sendPostAfterGettingPostFromId(Post data)
        //{
        //    var hubContext = GlobalHost.ConnectionManager.GetHubContext<MessagingHub>();
        //    //var tuple = Tuple.Create(data);
        //    try
        //    {
        //        ApiResponseModel<Post> model = new ApiResponseModel<Post>() { };
        //        var client = ServiceFactory.GetService(typeof(Post));
        //        data = await client.getPost(data.Id);

        //        model.data.records = data;

        //        hubContext.Clients.All.newPost(model);
        //    }
        //    catch (Exception ex)
        //    {
        //        hubContext.Clients.All.newPost(ex);
        //    }
        //}

        public static async void sendPost(Post data)
        {
            var hubContext = GlobalHost.ConnectionManager.GetHubContext <MessagingHub>();

            //var tuple = Tuple.Create(data);
            try
            {
                ApiResponseModel <Post> model = new ApiResponseModel <Post>()
                {
                };

                if (data.source == "2")
                {
                    User userData = new User();
                    var  client   = ServiceFactory.GetService(typeof(User));
                    userData = await client.getUserEntity(data.Createdby);

                    data.Createdby = userData.Name;
                    data.subject   = userData.Name;
                    data.image     = userData.image;
                    data.text      = Post.convertPostMentionsToBold(data.text);
                    //}
                    model.data.records = data;
                    if (data != null)
                    {
                        hubContext.Clients.All.newPost(model);
                    }
                }
                else if (data.source == "1")
                {
                    if (clients.ContainsKey(data.UserId))
                    {
                        bool result = await MazikCareService.Core.Authentication.ValidateToken(clients[data.UserId]["token"]);

                        if (result)
                        {
                            data = Post.retrieveFormattedAutoPost(data);
                            model.data.records = data;
                        }
                        else
                        {
                            List <string> listErrors = new List <string>();
                            listErrors.Add("User not Authorized");
                            Error error = new Error();
                            error.message = listErrors;
                            List <Error> list = new List <Error>();
                            list.Add(error);
                            model.error = list;
                        }
                        if (data != null)
                        {
                            hubContext.Clients.All.newPost(model);
                        }
                    }
                    else
                    {
                        // User not registered in Signal R dictionary
                    }
                }

                /*if(userId.Length > 0)
                 * {
                 *  hubContext.Clients.Client(connectionIdAndUserId[userId]).newPost(model);
                 *
                 * }
                 * else
                 * {*/
                //hubContext.Clients.All.newPost(model);

                //}
            }
            catch (Exception ex)
            {
                hubContext.Clients.All.newPost(ex);
            }
        }
Ejemplo n.º 17
0
        public ApiResponseModel <string> AddBroadcastFiles([FromForm] List <IFormFile> imageFile, [FromHeader] string displayLanguage)
        {
            string imageFilePath = null;
            var    responseModel = new ApiResponseModel <string>()
            {
                DisplayLanguage = displayLanguage
            };

            //sonraki işlemlerde bu kontrol kaldırılabilir.
            if (imageFile != null && imageFile.Count > 1)
            {
                responseModel.ResultStatusCode    = ResultStatusCodeStatic.Error;
                responseModel.ResultStatusMessage = "sadece 1 resim ekleyebilirsiniz.";
                return(responseModel);
            }

            //resim eklenmiş ise;
            if (imageFile != null && imageFile.Count > 0)
            {
                long size = imageFile.Sum(f => f.Length);
                try
                {
                    foreach (var item in imageFile)
                    {
                        List <string> allowedExtensions = ConfigHelper.ImageExtension;
                        string        fileExtension     = Path.GetExtension(item.FileName).ToLower();
                        bool          isAllowed         = allowedExtensions.Contains(fileExtension);
                        if (isAllowed)
                        {
                            if (item.Length > 0)
                            {
                                // full path to file in temp location
                                var filePath = Path.Combine(_hostingEnvironment.WebRootPath, "BroadcastFiles");

                                //mac cihazlarda -> image isminde boşluk oldugunda url olarak algılamamaktadır. bu yuzden replace ediyoruz.
                                var newImageName     = Guid.NewGuid().ToString() + item.FileName.Replace(" ", "");
                                var fileNameWithPath = string.Concat(filePath, "\\", newImageName);
                                imageFilePath = newImageName;
                                using (var stream = new FileStream(fileNameWithPath, FileMode.Create))
                                {
                                    item.CopyTo(stream);
                                }
                            }
                            else
                            {
                                responseModel.ResultStatusCode    = ResultStatusCodeStatic.Error;
                                responseModel.ResultStatusMessage = "Picture Format Incompatible";
                                return(responseModel);
                            }
                        }
                        else
                        {
                            responseModel.ResultStatusCode    = ResultStatusCodeStatic.Error;
                            responseModel.ResultStatusMessage = "Picture Format Incompatible";
                            return(responseModel);
                        }
                    }
                }
                catch
                {
                    responseModel.ResultStatusCode    = ResultStatusCodeStatic.Error;
                    responseModel.ResultStatusMessage = "Images Could Not Be Saved";
                    return(responseModel);
                }
            }
            else
            {
                responseModel.ResultStatusCode    = ResultStatusCodeStatic.Error;
                responseModel.ResultStatusMessage = "Images Could Not Be Saved";
                return(responseModel);
            }
            responseModel.Data                = imageFilePath;
            responseModel.ResultStatusCode    = ResultStatusCodeStatic.Success;
            responseModel.ResultStatusMessage = "Success";
            return(responseModel);
        }