Exemplo n.º 1
0
        public ValidateResponse DoValidate(ValidateData validatePayment)
        {
            ValidateResponse response = null;

            Dictionary <string, string> headers = new Dictionary <string, string>();

            headers.Add("apikey", this.validateApiKey);
            headers.Add("X-Consumer-Username", this.merchant);
            headers.Add("Cache-Control", "no-cache");

            this.restClientValidate = new RestClient(this.request_host + "/web/", headers, CONTENT_TYPE_APP_JSON);

            RestResponse result = this.restClientValidate.Post("validate", ValidateData.toJson(validatePayment));

            if (!String.IsNullOrEmpty(result.Response))
            {
                response = JsonConvert.DeserializeObject <ValidateResponse>(result.Response);
            }

            response.statusCode = result.StatusCode;

            if (result.StatusCode != STATUS_CREATED)
            {
                if (isErrorResponse(result.StatusCode))
                {
                    throw new ValidateResponseException(result.StatusCode.ToString(), JsonConvert.DeserializeObject <ErrorResponse>(result.Response));
                }
                else
                {
                    throw new ValidateResponseException(result.StatusCode + " - " + result.Response, response);
                }
            }

            return(response);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Validates the user is online.
        /// 项目用到的
        /// </summary>
        /// <param name="validateRequest">The login request.</param>
        /// <returns></returns>
        public ValidateResponse ValidateUserIsOnline(ValidateRequest validateRequest)
        {
            ValidateResponse loginResponse = new ValidateResponse();
            User             user          = validateRequest.User;

            try
            {
                lock (synchronizeObjectCall)
                {
                    // User is not yet logged in.
                    if (iPow.Service.SSO.WebService.OnLineUserService
                        .OnLineUserList.Where(e => e.id == user.id && e.username == user.username).Any())
                    {
                        //存在
                        loginResponse.User = user;
                    }
                }
            }
            catch (Exception ex)
            {
                loginResponse.Fault         = new SingleSignOnFault();
                loginResponse.Fault.Message = ex.Message;
            }
            return(loginResponse);
        }
Exemplo n.º 3
0
        public ValidateResponse FixAttributeNameToLabel(ServiceKey sk, ValidateResponse vr)
        {
            ValidateResponse resp = new ValidateResponse(true);
            var atts   = ServiceAttributes.Get(sk, false);
            var errors = vr.GetErrors();

            if (errors?.Count() > 0)
            {
                resp.IsValid = false;
                foreach (var err in errors)
                {
                    if (err.Description.Contains("[") && err.Description.Contains("]"))
                    {
                        var attName     = Regex.Match(err.Description, @"\[([^)]*)\]")?.Groups[1]?.Value;
                        var info        = atts.FirstOrDefault(x => x.Name == attName);
                        var description = err.Description.Replace("[" + attName + "]", info.Label);
                        resp.AddError(description, err.Category, err.Entity, err.Type, err.Reason, err.ErrorCode);
                    }
                    else
                    {
                        resp.AddError(err.Description, err.Category, err.Entity, err.Type, err.Reason, err.ErrorCode);
                    }
                }
            }
            return(resp);
        }
Exemplo n.º 4
0
        public ValidateResponse CreateNewServiceGroup(servicegroup serviceGroup)
        {
            ValidateResponse resposne = new ValidateResponse();

            try
            {
                using (var context = new FitnessProEntities()) {
                    IMapper      iMapper       = revMapConfig.CreateMapper();
                    ServiceGroup eServiceGroup = new ServiceGroup();
                    iMapper.Map(serviceGroup, eServiceGroup);
                    context.ServiceGroups.Add(eServiceGroup);
                    context.SaveChanges();
                    resposne.IsSuccess = true;
                }
            }
            catch (Exception ex)
            {
                resposne.IsSuccess          = false;
                resposne.ValidationMessages = new List <string> {
                    ex.ToString()
                };
            }

            return(resposne);
        }
        public static ValidateResponse Validate(ValidateRequest validateRequest)
        {
            ValidateResponse validateResponse = new ValidateResponse();

            ErrorResponse errorResponse = validateCredentials(credentials);
            string        responseCode  = errorResponse.responseCode;

            if (errorResponse.responseCode != "00")
            {
                validateResponse.responseCode = errorResponse.responseCode;
                validateResponse.responseMsg  = errorResponse.responseMsg;
                return(validateResponse);
            }

            if (validateRequest == null)
            {
                validateResponse.responseCode = "14";
                validateResponse.responseMsg  = "Missing Validate Request object";
                return(validateResponse);
            }

            String jsonValidateRequest = JsonConvert.SerializeObject(validateRequest);

            try
            {
                var response = WebClientUtil.PostResponse(credentials.url, RemitaBillerUrl.Validate(), jsonValidateRequest, _header);
                validateResponse = JsonConvert.DeserializeObject <ValidateResponse>(response);
            }
            catch (Exception)
            {
                throw;
            }
            return(validateResponse);
        }
Exemplo n.º 6
0
        public ValidateResponse ValidateMessage(string message)
        {
            if (string.IsNullOrWhiteSpace(message))
            {
                var list = new List <string>();
                list.Add("Empty message");
                return(new ValidateResponse()
                {
                    IsValid = false, ErrorList = list
                });
            }

            var objValidate = new ValidateResponse();

            objValidate.IsValid = true;
            foreach (var item in keyValidatorElements)
            {
                var beginingTag = Regex.Matches(message, string.Format("<{0}>", item.Value)).Count;
                var closingTag  = Regex.Matches(message, string.Format("</{0}>", item.Value)).Count;
                if (beginingTag != closingTag)
                {
                    objValidate.ErrorList.Add(string.Format("Missing {0} tag", item.Value));
                    objValidate.IsValid = false;
                }
            }

            if (Regex.Matches(message, "<total>").Count == 0)
            {
                objValidate.ErrorList.Add("Missing Total tag");
                objValidate.IsValid = false;
            }

            return(objValidate);
        }
        private static void CheckForValidation(IGuestControllerClient guestControllerClient, string displayName, Action <IValidateDisplayNameResult> callback)
        {
            ValidateRequest validateRequest = new ValidateRequest();

            validateRequest.displayName = displayName;
            ValidateRequest request = validateRequest;

            guestControllerClient.Validate(request, delegate(GuestControllerResult <ValidateResponse> r)
            {
                if (!r.Success)
                {
                    callback(new ValidateDisplayNameResult(success: false));
                }
                else
                {
                    ValidateResponse response = r.Response;
                    if (response.error == null)
                    {
                        callback(new ValidateDisplayNameResult(success: true));
                    }
                    else
                    {
                        callback(new ValidateDisplayNameExistsResult(success: false));
                    }
                }
            });
        }
        public HttpResponseMessage CreateIdentity([FromBody] Identity model, [FromHeader(Name = "opensheets-bypass-level")] Level bypassLevel = Level.Information)
        {
            if (model.PrincipalId != Context.Principal.Id && !Context.Identity.Flags.Contains(IdentityFlag.SysAdmin))
            {
                return(Request.CreateResponse(HttpStatusCode.Forbidden));
            }

            ValidateResponse validateResp = _router.Query <ValidateRequest <Identity>, ValidateResponse>(
                new ValidateRequest <Identity>()
            {
                ObjectId = Guid.Empty,
                Object   = model
            });

            if (validateResp.Results.Any(x => x.Level > Level.Information))
            {
                return(Request.CreateResponse((HttpStatusCode)422, new { Validation = new { Errors = validateResp.Results } }));
            }

            model.Id = Guid.NewGuid();

            _router.Command(new CreateCommand <Identity>()
            {
                Object = model
            });

            return(Request.CreateResponse(HttpStatusCode.OK, new { Id = model.Id }));
        }
Exemplo n.º 9
0
        public void AsValid_Should_Return_Correctly()
        {
            // ACT
            var response = ValidateResponse.AsValid();

            // ASSERT
            response.Valid.Should().BeTrue();
            response.Message.Should().BeNull();
        }
        internal static async Task Execute(Client client)
        {
            ValidateCommand command = new ValidateCommand
            {
                Base64Xml = "Base64Xml"
            };
            ValidateResponse result = await client.PeppolDocuments.ValidateAsync(command);

            Console.WriteLine($"Is valid: ", result.IsValid);
        }
Exemplo n.º 11
0
 public HttpStatusCode CreateNewServiceGroup([FromBody] servicegroup serviceGroup)
 {
     if (ModelState.IsValid)
     {
         ValidateResponse response = _serviceGroupManager.CreateNewServiceGroup(serviceGroup);
         if (response.IsSuccess)
         {
             return(HttpStatusCode.Created);
         }
     }
     return(HttpStatusCode.BadRequest);
 }
Exemplo n.º 12
0
        public void AsInvalid_Should_Return_Correctly()
        {
            // ARRANGE
            var message = Guid.NewGuid().ToString();

            // ACT
            var response = ValidateResponse.AsInvalid(message);

            // ASSERT
            response.Valid.Should().BeFalse();
            response.Message.Should().Be(message);
        }
Exemplo n.º 13
0
        public string sendMail(UsedCarMailContent md)
        {
            ResultInfo r = new ResultInfo();

            #region 驗證碼
            ValidateResponse Validate = ValidateCaptcha(md.response);
            if (!Validate.Success)
            {
                r.result  = false;
                r.message = Resources.Res.Log_Err_googleValideNotEquel;
                return(defJSON(r));
            }
            #endregion
            try
            {
                using (db0 = getDB0())
                {
                    if (md.email == null)
                    {
                        r.result  = false;
                        r.message = Resources.Res.Log_Err_MailAddressBlank;
                        return(defJSON(r));
                    }
                    #region 信件發送
                    string  Body = getMailBody("UsedCarEmail", md);//套用信件版面
                    Boolean mail;
                    string  mailfrom = md.name + ":" + "*****@*****.**";

                    mail = Mail_Send(mailfrom,                       //寄信人
                                     openLogic().getReceiveMails(),  //收信人
                                     CommWebSetup.MailTitle_UsedCar, //信件標題
                                     Body,                           //信件內容
                                     true);                          //是否為html格式
                    if (mail == false)
                    {
                        r.result  = false;
                        r.message = Resources.Res.Log_Err_SendMailFail;
                        return(defJSON(r));
                    }
                    #endregion
                }
                r.result  = true;
                r.message = Resources.Res.Log_Success_SendMail;
            }
            catch (Exception ex)
            {
                r.result  = false;
                r.message = ex.Message;
            }
            return(defJSON(r));
        }
Exemplo n.º 14
0
        public string sendMail(ContactUsMailContent md)
        {
            ResultInfo r = new ResultInfo();

            #region 驗證碼
            ValidateResponse Validate = ValidateCaptcha(md.response, "6LexIhoTAAAAAL-SrVm8_fYcL7pTnovF4T7GozRx");
            if (!Validate.Success)
            {
                r.result  = false;
                r.message = Resources.Res.Log_Err_googleValideNotEquel;
                return(defJSON(r));
            }
            #endregion
            try
            {
                using (db0 = getDB0())
                {
                    if (md.email == null)
                    {
                        r.result  = false;
                        r.message = Resources.Res.Log_Err_MailAddressBlank;
                        return(defJSON(r));
                    }
                    #region 信件發送
                    string  Body = getMailBody("ContactUsEmail", md);//套用信件版面
                    Boolean mail;
                    string  mailfrom = md.name + ":" + md.email;

                    mail = Mail_Send(mailfrom,                                                                //寄信人
                                     openLogic().getReceiveMails(),                                           //收信人
                                     string.Format(CommWebSetup.MailTitle, md.country, md.company, md.title), //信件標題
                                     Body,                                                                    //信件內容
                                     true);                                                                   //是否為html格式
                    if (mail == false)
                    {
                        r.result  = false;
                        r.message = Resources.Res.Log_Err_SendMailFail;
                        return(defJSON(r));
                    }
                    #endregion
                }
                r.result  = true;
                r.message = Resources.Res.Log_Success_SendMail;
            }
            catch (Exception ex)
            {
                r.result  = false;
                r.message = ex.Message;
            }
            return(defJSON(r));
        }
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Initiate the method to create any data that this sample requires.
        /// Verify whether an appointment has valid resources for the appointment activity.
        /// Optionally delete any entity records that were created for this sample.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    // Call the method to create any data that this sample requires.
                    CreateRequiredRecords();

                    //<snippetValidate1>

                    // Retrieve the appointment to be validated
                    ColumnSet   cols = new ColumnSet("scheduledstart", "scheduledend", "statecode", "statuscode");
                    Appointment retrievedAppointment = (Appointment)_serviceProxy.Retrieve(Appointment.EntityLogicalName,
                                                                                           _appointmentId, cols);

                    // Use the Validate message
                    ValidateRequest validatedReq = new ValidateRequest();
                    validatedReq.Activities = new EntityCollection();
                    validatedReq.Activities.Entities.Add(retrievedAppointment);
                    validatedReq.Activities.MoreRecords  = false;
                    validatedReq.Activities.PagingCookie = "";
                    validatedReq.Activities.EntityName   = Appointment.EntityLogicalName;

                    ValidateResponse validateResp = (ValidateResponse)_serviceProxy.Execute(validatedReq);

                    // Verify success
                    if ((validateResp.Result != null) && (validateResp.Result.Length > 0))
                    {
                        Console.WriteLine("Validated the appointment.");
                    }
                    //</snippetValidate1>

                    DeleteRequiredRecords(promptForDelete);
                }
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Exemplo n.º 16
0
        public static ValidateResponse Validate(this Parameters parameters)
        {
            var isFileNameBlank = string.IsNullOrWhiteSpace(parameters.FileName);

            if (isFileNameBlank)
            {
                return(ValidateResponse.AsInvalid("FileName is required."));
            }

            var fileName          = Path.GetFileName(parameters.FileName);
            var isFileNameInvalid = Path.GetInvalidFileNameChars().Any(c => fileName.Contains(c));
            var directoryName     = Path.GetDirectoryName(parameters.FileName);
            var isPathInvalid     = Path.GetInvalidPathChars().Any(c => directoryName.Contains(c));

            if (isFileNameInvalid || isPathInvalid)
            {
                return(ValidateResponse.AsInvalid("Invalid FileName."));
            }

            var isDirectoryValid = string.IsNullOrWhiteSpace(directoryName) ? true : Directory.Exists(directoryName);

            if (!isDirectoryValid)
            {
                return(ValidateResponse.AsInvalid("Directory does not exist."));
            }
            ;

            // even though Default is part of ContentFillType it is still considered an invalid value
            //   because this should have been updated when parsing the received arguments
            var isContentFillDefault = parameters.ContentFill == ContentFillType.Default;

            if (isContentFillDefault)
            {
                return(ValidateResponse.AsInvalid("Invalid --FILL value."));
            }

            // ContentTemplate is required unless ContentFill is ContentFillType.Null
            var isContentTemplateBlank  = string.IsNullOrWhiteSpace(parameters.ContentTemplate);
            var isContentTemplateNeeded = parameters.ContentFill != ContentFillType.Null && isContentTemplateBlank;

            if (isContentTemplateNeeded)
            {
                return(ValidateResponse.AsInvalid("Invalid --CONTENT value."));
            }

            return(ValidateResponse.AsValid());
        }
Exemplo n.º 17
0
        public static ValidateResponse Validate(ServiceKey key)
        {
            var response = new ValidateResponse(true, key);
            var kids     = Get(key);

            // validate min/max
            foreach (var kid in kids)
            {
                if (kid.MinQuantity > 0 &&
                    (key.Children == null || !key.Children.ContainsKey(kid.Name) || key.Children[kid.Name].Count < kid.MinQuantity))
                {
                    response.AddError($"Minimum quanity not met for child '{kid.Name}'", ValidationError.SERVICE, key.GetIdentifier(null), ValidationError.MINIMUM, "Minimum quantity not met");
                }
                else if (kid.MaxQuantity >= 0 &&
                         key.Children != null &&
                         key.Children.ContainsKey(kid.Name) &&
                         key.Children[kid.Name].Count > kid.MaxQuantity)
                {
                    response.AddError($"Too many instances of child '{kid.Name}'", ValidationError.SERVICE, key.GetIdentifier(null), ValidationError.MAXIMUM, "Maximum quantity exceeded");
                }
            }
            // make sure we don't have any extras
            if (key.Children != null)
            {
                foreach (var child in key.Children)
                {
                    var allowedIds = kids.Where(k => k.Name.Equals(child.Key)).Select(k => k.Id);
                    if (allowedIds.Count() == 0)
                    {
                        response.AddError($"Child '{child.Key}' is not allowed on this service", ValidationError.SERVICE, key.GetIdentifier(null), ValidationError.MAXIMUM, $"Child '{child.Key}' is not allowed");
                    }
                    else
                    {
                        foreach (var v in child.Value)
                        {
                            if (!allowedIds.Contains(v.Id))
                            {
                                response.AddError($"Service #{v.Id} is not allowed for child '{child.Key}'", ValidationError.SERVICE, key.GetIdentifier(null), ValidationError.MAXIMUM, $"Service #{v.Id} is not allowed");
                            }
                        }
                    }
                }
            }

            return(response);
        }
Exemplo n.º 18
0
        private NodeBodyUpdate GetSignerProperties(ValidateResponse pdfValidation, ValidateCertificateResponse certValidation, bool isSigned)
        {
            var publisher = Dn.Parse(pdfValidation?.Report?.sigInfos[0]?.signCert?.Issuer);
            var holder    = Dn.Parse(pdfValidation?.Report?.sigInfos[0]?.signCert?.Subject);
            var verifier  = Dn.Parse(GetVerifier(pdfValidation?.XMLReport));

            return(new NodeBodyUpdate()
                   .AddProperty(SpisumNames.Properties.FileIsSigned, isSigned)
                   .AddProperty(SpisumNames.Properties.UsedTime, pdfValidation?.Report?.CreationDateTime)
                   .AddProperty(SpisumNames.Properties.VerificationTime, pdfValidation?.Report?.validationProperties?.ValidationTime)
                   .AddProperty(SpisumNames.Properties.ValiditySafetyElement, pdfValidation?.Report?.globalStatus switch
            {
                SignerNames.Ok => SpisumNames.Signer.Valid,
                SignerNames.Warning => SpisumNames.Signer.ValidityAssessed,
                SignerNames.Error => SpisumNames.Signer.NotValid,
                _ => null
            })
        public HttpResponseMessage CreateFile(Guid userId, Guid directoryId, Core.File fileData)
        {
            if (fileData.DirectoryId == Guid.Empty)
            {
                fileData.DirectoryId = directoryId;
            }

            CheckPermissionResponse permissionResponse = _router.Query <CheckPermissionRequest, CheckPermissionResponse>(new CheckPermissionRequest()
            {
                IdentityId = Context.Identity.Id,
                OwnerId    = userId,
                FileId     = directoryId
            });

            bool canWrite = false;

            if (!permissionResponse.EffectivePermissions.TryGetValue(FilePermissionAction.Write, out canWrite) || !canWrite)
            {
                return(Request.CreateResponse(HttpStatusCode.Forbidden));
            }

            fileData.Id = Guid.NewGuid();

            ValidateResponse validateResp = _router.Query <ValidateRequest <Core.File>, ValidateResponse>(new ValidateRequest <Core.File>()
            {
                ObjectId = fileData.Id,
                Object   = fileData
            });

            if (validateResp.Results.Any(x => x.Level > Level.Information))
            {
                return(Request.CreateResponse((HttpStatusCode)422, new { Validation = new { Errors = validateResp.Results } }));
            }

            _router.Command(new CreateCommand <Core.File>()
            {
                Object = fileData
            });

            return(Request.CreateResponse(HttpStatusCode.OK, new { FileId = fileData.Id }));
        }
 private static void Send(AbstractLogger logger, IGuestControllerClient guestControllerClient, ValidateRequest request, Action <IValidateNewAccountResult> callback)
 {
     try
     {
         guestControllerClient.Validate(request, delegate(GuestControllerResult <ValidateResponse> r)
         {
             if (!r.Success)
             {
                 callback(new ValidateNewAccountResult(success: false, null));
             }
             else
             {
                 ValidateResponse response = r.Response;
                 if (response.error == null)
                 {
                     callback(new ValidateNewAccountResult(success: true, null));
                 }
                 else
                 {
                     IValidateNewAccountResult validateResult = GuestControllerErrorParser.GetValidateResult(response.error);
                     if (validateResult != null)
                     {
                         callback(validateResult);
                     }
                     else
                     {
                         IEnumerable <IValidateNewAccountError> validationErrors = GuestControllerErrorParser.GetValidationErrors(response.error);
                         callback(new ValidateNewAccountResult(success: false, validationErrors));
                     }
                 }
             }
         });
     }
     catch (Exception arg)
     {
         logger.Critical("Unhandled exception: " + arg);
         callback(new ValidateNewAccountResult(success: false, null));
     }
 }
Exemplo n.º 21
0
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            Payment payment = new Payment();

            var key           = payment.GetEncryptionKey(Secretkey);
            var json          = JsonConvert.SerializeObject(GetData());
            var encryptedData = payment.EncryptData(key, json);

            PayLoad        postData      = GetPayLoad(encryptedData);
            var            jsondata      = JsonConvert.SerializeObject(postData);
            ChargeResponse chargeReponse = await payment.SuggestCardType(chargeEndpoint, jsondata);

            if (chargeReponse != null && chargeReponse.status == "success" && chargeReponse.data.suggested_auth == "PIN")
            {
                var          rawJsonDataInit      = JsonConvert.SerializeObject(GetData(chargeReponse.data.suggested_auth, "3310"));
                var          encryptedDataInit    = payment.EncryptData(key, rawJsonDataInit);
                PayLoad      payloadInit          = GetPayLoad(encryptedDataInit);
                var          encrptedjsondataInit = JsonConvert.SerializeObject(payloadInit);
                CardResponse cardReponse          = await payment.InitializePayment(chargeEndpoint, encrptedjsondataInit);

                if (cardReponse != null && cardReponse.data.chargeResponseCode == "02" && cardReponse.data.authModelUsed == "PIN")
                {
                    var dataRf = new
                    {
                        PBFPubKey             = PublicKey,
                        transaction_reference = cardReponse.data.txRef,
                        otp = "12345"
                    };
                    var jsondf = JsonConvert.SerializeObject(dataRf);
                    ValidateResponse valReps = await payment.ValidatePayment(validationEndpoint, jsondf);
                }
            }
            else if (chargeReponse.status == "error")
            {
            }
        }
Exemplo n.º 22
0
        public async Task <IActionResult> Post(ValidationRequest request)
        {
            HttpClient       client           = null;
            ValidateResponse validateResponse = null;

            try
            {
                var path = request.URL;
                Guard.Against.Null(path, nameof(path));
                string schemaPath = Path.Combine($"{AppDomain.CurrentDomain.BaseDirectory}/schema", _cfg.GetValue <string>("SchemaName"));
                client = _clientFactory.CreateClient();
                client.DefaultRequestHeaders.Accept.Clear();
                client.BaseAddress = new Uri(path);
                Guard.Against.Null("Token", request.Headers["Authorization"]);
                int Authorization = request.Headers["Authorization"].Trim().Length;
                Guard.Against.Zero(Authorization, nameof(Authorization));
                foreach (string key in request.Headers.Keys)
                {
                    if (key.Trim() == "Authorization")
                    {
                        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", request.Headers[key]);
                    }
                    else
                    {
                        client.DefaultRequestHeaders.Add(key, request.Headers[key]);
                    }
                }
                client.Timeout = TimeSpan.FromSeconds(_cfg.GetValue <int>("TimeOut"));
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));

                string jsontovalidate        = "";
                HttpResponseMessage response = null;

                response = await client.GetAsync(path);

                if (response.IsSuccessStatusCode)
                {
                    jsontovalidate = await response.Content.ReadAsStringAsync();

                    string validjsonschema = System.IO.File.ReadAllText(schemaPath);
                    JsonSchemaValidator schemaController = new JsonSchemaValidator();
                    ValidateRequest     validateRequest  = new ValidateRequest();
                    validateRequest.Json   = jsontovalidate;
                    validateRequest.Schema = validjsonschema;
                    validateResponse       = schemaController.Validate(validateRequest);
                }
                else
                {
                    validateResponse       = new ValidateResponse();
                    validateResponse.Valid = false;
                    Guard.Against.Null(response, nameof(response));
                    if (response != null)
                    {
                        validateResponse.Validations = new List <string>();
                        validateResponse.Validations.Add("Status from API Call=>" + response.StatusCode.ToString());
                    }
                }
            }
            catch (Exception e)
            {
                return(StatusCode((int)HttpStatusCode.InternalServerError, e.Message));
            }
            finally
            {
            }
            return(Ok(validateResponse));
        }
Exemplo n.º 23
0
        /// <summary>
        /// 验证用户 // Edit By Cyrano
        /// </summary>
        /// <returns></returns>
        public string Validate()
        {
            string returnStr = string.Empty;

            if (Signature != GetParam("sig").ToString())
            {
                ErrorCode = (int)ErrorType.API_EC_SIGNATURE;
                return returnStr;
            }

            if (CallId <= LastCallId)
            {
                ErrorCode = (int)ErrorType.API_EC_CALLID;
                return returnStr;
            }

            if (!CheckRequiredParams("user_name,password"))
            {
                ErrorCode = (int)ErrorType.API_EC_PARAM;
                return returnStr;
            }

            if (this.App.ApplicationType == (int)ApplicationType.DESKTOP)//如果是桌面程序则不允许此方法
            {
                if (Uid < 1 || Discuz.Forum.UserGroups.GetUserGroupInfo(Discuz.Forum.Users.GetShortUserInfo(Uid).Groupid).Radminid != 1)
                {
                    ErrorCode = (int)ErrorType.API_EC_PERMISSION_DENIED;
                    return "";
                }
            }
            else if (Uid > 0)//已经登录的用户不能再验证
            {
                ErrorCode = (int)ErrorType.API_EC_USER_ONLINE;
                return returnStr;
            }

            string username = GetParam("user_name").ToString();
            string password = GetParam("password").ToString();

            bool isMD5Passwd = GetParam("password_format") != null && GetParam("password_format").ToString() == "md5" ? true : false;

            //用户名不符合规范
            //if (!CheckUsername(username))
            //{
            //    ErrorCode = (int)ErrorType.API_EC_USERNAME_ILLEGAL;
            //    return returnStr;
            //}

            if (Discuz.Forum.Users.GetUserId(username) == 0)//如果用户名符合注册规则, 则判断是否已存在
            {
                ErrorCode = (int)ErrorType.API_EC_USER_NONEXIST;
                return returnStr;
            }

            if (!isMD5Passwd && password.Length < 6)
            {
                ErrorCode = (int)ErrorType.API_EC_PARAM;
                return returnStr;
            }

            ShortUserInfo userInfo = new ShortUserInfo();
            var postpassword =  password;
            var postusername = username;
            int uid = -1;

            uid = Discuz.Forum.Users.CheckPassword(postusername, postpassword, !isMD5Passwd);
            userInfo = uid > 0 ? Discuz.Forum.Users.GetShortUserInfo(uid) : null;

            if (userInfo != null)
            {
                #region 当前用户所在用户组为"禁止访问"或"等待激活"时

                if (userInfo.Groupid == 5 || userInfo.Groupid == 8)// 5-禁止访问, 8-等待激活
                {
                    ErrorCode = (int)ErrorType.API_EC_USERNAME_ILLEGAL;
                    return returnStr;
                }

                #endregion
            }
            else
            {
                int errcount = LoginLogs.UpdateLoginLog(DNTRequest.GetIP(), true);

                if (errcount > 5)
                {
                    //AddErrLine("您已经输入密码5次错误, 请15分钟后再试");
                }
                else
                {
                    //AddErrLine(string.Format("密码或安全提问第{0}次错误, 您最多有5次机会重试", errcount));
                }
            }

            //ForumUtils.WriteUserCreditsCookie(userInfo, usergroupinfo.Grouptitle);

            if (Format == FormatType.JSON)
                return string.Format("\"{0}\"", userInfo.Uid);

            ValidateResponse vr = new ValidateResponse();
            vr.Uid = userInfo.Uid;

            return SerializationHelper.Serialize(vr);
        }
Exemplo n.º 24
0
        public ValidateServiceResponse Validate(ServiceKey key)
        {
            var response = new ValidateServiceResponse(true, key)
            {
                Errors = new List <IValidationError>()
            };
            var vr = new ValidateResponse(true, key)
            {
                Errors = new List <IValidationError>()
            };

            // let's make sure all required attributes are there
            vr.Errors.AddRange(from ad in Attributes.Values
                               where !IsOptional(ad.Name, key)
                               //checking if the attribute is supposed to have defaults
                               where !HasDefault(ad.Name)
                               where !ad.Type.Equals(AttributeType.Complex)
                               let value = key.GetAttributeValue(ad.Name, SearchOptions.ALL_TRUE)
                                           where string.IsNullOrEmpty(value)
                                           select new ValidationServiceError(string.Format("{0}: {1} is required.", key.ServiceInstanceId, ad.Label), ValidationError.SERVICE, ad.Name, ValidationError.MISSING, ad.Label, null, key.ServiceInstanceId));

            // if attributes are missing, let's stop there
            if (vr.Errors.Count == 0)
            {
                // valid value check
                var validValueRules = ValidValueRuleParser.GetRules(ValidValueRule);

                foreach (IValidValueRule rule in validValueRules)
                {
                    var v = key.GetAttributeValue(rule.GetAttributeName(), SearchOptions.NO_DEFAULTS);
                    //checking if attribute is applicable and is required
                    if (IsConfigurableAttribute(rule.GetAttributeName(), key) && !IsOptional(rule.GetAttributeName(), key))
                    {
                        vr.AddResponse(rule.ValidateAttributes(key));
                    }
                }

                // DataConstraints
                foreach (var a in key.Values)
                {
                    vr.AddResponse(IsValid(a.Key, a.Value.Value, key));
                }


                // service relationships
                vr.AddResponse(ServiceRelationships.ValidateRelationships(key));


                // children
                vr.AddResponse(ServiceHierarchy.Validate(key));



                //Since we have all of the needed values, we can now make sure that it meets all of the business rules.
                var           attributes = ServiceAttributes.Get(key, false);
                AttributeInfo attributeInfo;
                foreach (var attributeName in Attributes.Keys)
                {
                    attributeInfo = attributes.FirstOrDefault(a => a.Name.Equals(attributeName));
                    if (attributeInfo != null)
                    {
                        if (attributeInfo.GetValue() == null && !IsOptional(attributeName, key) && !HasDefault(attributeName))
                        {
                            vr.AddError(attributeInfo.Label + " does not have a valid value.", ValidationError.ATTRIBUTE, key.GetIdentifier(null), ValidationError.INVALID_VALUE, attributeName);
                        }
                        //If the value returned by the GetAttributes doesn't match the one returned by the key, we are not valid.
                        if (attributeInfo.Type.Equals(AttributeType.List))
                        {
                            string value = null;
                            if (!string.IsNullOrEmpty(attributeInfo.GetValue()))
                            {
                                value = attributeInfo.GetValue();
                            }
                            else if (!string.IsNullOrEmpty(attributeInfo.DefaultValue))
                            {
                                value = attributeInfo.DefaultValue;
                            }

                            var keyValue = key.GetAttributeValue(attributeName, SearchOptions.ALL_TRUE);
                            if (value != null && keyValue != null && !value.Equals(keyValue))
                            {
                                vr.AddError(string.Format("{0} ({1}) does not have a valid value. Should be ({2}).",
                                                          attributeInfo.Label, keyValue, value), ValidationError.ATTRIBUTE, key.GetIdentifier(null), ValidationError.INVALID_VALUE, attributeName);
                            }
                        }
                    }
                    else if (!HasDefault(attributeName) && !IsOptional(attributeName, key))
                    {
                        vr.AddError(
                            string.Format("{0} is required, does not have a default value, and '{1}' is not returned by GetAttributes.",
                                          attributeInfo.Label, key.GetAttributeValue(attributeName, SearchOptions.ALL_TRUE)),
                            ValidationError.ATTRIBUTE, key.GetIdentifier(null), ValidationError.INVALID_VALUE, attributeName);
                    }
                }
            }
            response.AddResponse(response.ToServiceResponse(FixAttributeNameToLabel(key, vr)));

            if (response.Errors.Count > 0)
            {
                response.IsValid = false;
                List <ValidationServiceError> vErrors = new List <ValidationServiceError>();

                foreach (var error in response.Errors)
                {
                    if (error is ValidationError)
                    {
                        vErrors.Add(new ValidationServiceError(error.Description, error.Category,
                                                               error.Entity, error.Type, error.Reason, error.ErrorCode, key.ServiceInstanceId));
                    }
                    else
                    {
                        if ((error as ValidationServiceError)?.InstanceId == null || (error as ValidationServiceError)?.InstanceId == 0)
                        {
                            vErrors.Add(new ValidationServiceError(error.Description, error.Category,
                                                                   error.Entity, error.Type, error.Reason, error.ErrorCode, key.ServiceInstanceId));
                        }
                        else
                        {
                            vErrors.Add(error as ValidationServiceError);
                        }
                    }
                }
                if (vErrors.Count > 0)
                {
                    response.Errors = null;
                    response.AddErrors(new List <ValidationServiceError>(vErrors));
                }
            }

            return(response);
        }
Exemplo n.º 25
0
        public async Task <string> member_Login(LoginViewModel model)
        {
            LoginResult getLoginResult = new LoginResult();

            #region 驗證碼檢查程序

#if DEBUG
            getLoginResult.vildate = true;
#else
            #region Google驗證
            //if (!ModelState.IsValid)
            //{
            //    getLoginResult.result = false;
            //    getLoginResult.message = Resources.Res.Login_Err_Normal;
            //    return defJSON(getLoginResult);
            //}
            ValidateResponse Validate = ValidateCaptcha(model.validate);
            getLoginResult.vildate = Validate.Success;
            #endregion
#endif
            if (!getLoginResult.vildate)
            {
                //Session["CheckCode"] = Guid.NewGuid();//只要有錯先隨意產生唯一碼 以防暴力破解,新的CheckCode會在Validate產生。
                getLoginResult.result  = false;
                getLoginResult.message = Resources.Res.Log_Err_googleValideNotEquel;
                return(defJSON(getLoginResult));
            }
            #endregion

            try
            {
                #region 帳密碼檢查

                using (var db0 = getDB0())
                {
                    string pw       = Server.UrlEncode(EncryptString.desEncryptBase64(model.password));
                    var    get_user = await db0.Customer.Where(x => x.email == model.account& x.c_pw == pw).FirstOrDefaultAsync();

                    bool check_account = await db0.Customer.AnyAsync(x => x.email == model.account);

                    if (get_user != null)
                    {
                        #region 前台_會員登入用cookie

                        string userData                  = "Customers";
                        string encode_userid             = Server.UrlEncode(EncryptString.desEncryptBase64(get_user.customer_id.ToString()));//userid 加密
                        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, encode_userid, DateTime.Now, DateTime.Now.AddMinutes(300), false, userData, FormsAuthentication.FormsCookiePath);

                        string encTicket = FormsAuthentication.Encrypt(ticket);
                        Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));

                        var cookie_loginid = new HttpCookie(CommWebSetup.LoginId, encode_userid);
                        cookie_loginid.HttpOnly = true;
                        cookie_loginid.SameSite = SameSiteMode.Lax;
                        if (Request.IsSecureConnection)
                        {
                            cookie_loginid.Secure = true;
                        }
                        Response.Cookies.Add(cookie_loginid);

                        //LoginType //N:管理者登錄 Y:一般會員登錄
                        var cookie_login_type = new HttpCookie(CommWebSetup.LoginType, Server.UrlEncode(EncryptString.desEncryptBase64("Y")));
                        cookie_login_type.HttpOnly = true;
                        cookie_login_type.SameSite = SameSiteMode.Lax;
                        if (Request.IsSecureConnection)
                        {
                            cookie_login_type.Secure = true;
                        }
                        Response.Cookies.Add(cookie_login_type);

                        #endregion
                        #region 後台_會員登入用cookie
                        Session["CheckCode"] = "jcin";

                        #endregion

                        getLoginResult.result = true;
                        string result_url = Url.Content(CommWebSetup.MemberDefCTR);

                        getLoginResult.url = result_url;
                        return(defJSON(getLoginResult));
                    }
                    else
                    {
                        if (!check_account)
                        {
                            getLoginResult.nothaveAccount = true;
                            getLoginResult.url            = Url.Content(CommWebSetup.MemberRegisterCTR);
                        }
                        getLoginResult.result  = false;
                        getLoginResult.message = Resources.Res.Login_Err_Password;//帳號或密碼錯誤 請重新輸入
                        return(defJSON(getLoginResult));
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                getLoginResult.result  = false;
                getLoginResult.message = ex.Message;
                return(defJSON(getLoginResult));
            }
        }
Exemplo n.º 26
0
        [STAThread] // Added to support UX
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    #region Sample Code
                    #region Set up
                    SetUpSample(service);
                    #endregion Set up
                    #region Demonstrate
                    // Retrieve the appointment to be validated
                    ColumnSet   cols = new ColumnSet("scheduledstart", "scheduledend", "statecode", "statuscode");
                    Appointment retrievedAppointment = (Appointment)service.Retrieve(Appointment.EntityLogicalName,
                                                                                     _appointmentId, cols);

                    // Use the Validate message
                    ValidateRequest validatedReq = new ValidateRequest();
                    validatedReq.Activities = new EntityCollection();
                    validatedReq.Activities.Entities.Add(retrievedAppointment);
                    validatedReq.Activities.MoreRecords  = false;
                    validatedReq.Activities.PagingCookie = "";
                    validatedReq.Activities.EntityName   = Appointment.EntityLogicalName;

                    ValidateResponse validateResp = (ValidateResponse)service.Execute(validatedReq);

                    // Verify success
                    if ((validateResp.Result != null) && (validateResp.Result.Length > 0))
                    {
                        Console.WriteLine("Validated the appointment.");
                    }

                    #region Clean up
                    CleanUpSample(service);
                    #endregion Clean up
                }
                #endregion Demonstrate
                #endregion Sample Code
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Common Data Service";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
Exemplo n.º 27
0
        public async Task <string> ajax_Login(LoginViewModel model)
        {
            var userManager = UserManager;

            LoginResult getLoginResult = new LoginResult();


            #region 驗證碼檢查程序

#if DEBUG
            getLoginResult.vildate = true;
#else
            //if (string.IsNullOrEmpty(Session["CheckCode"].ToString()))
            //{
            //    Session["CheckCode"] = Guid.NewGuid();
            //    getLoginResult.result = false;
            //    getLoginResult.message = Resources.Res.Log_Err_ImgValideNotEquel;
            //    return defJSON(getLoginResult);
            //}

            //getLoginResult.vildate = Session["CheckCode"].Equals(model.validate) ? true : false;
            ValidateResponse Validate = ValidateCaptcha(model.validate);
            getLoginResult.vildate = Validate.Success;
#endif
            if (!getLoginResult.vildate)
            {
                //Session["CheckCode"] = Guid.NewGuid(); //只要有錯先隨意產生唯一碼 以防暴力破解,新的CheckCode會在Validate產生。
                getLoginResult.result  = false;
                getLoginResult.message = Resources.Res.Log_Err_ImgValideNotEquel;
                return(defJSON(getLoginResult));
            }
            #endregion

            #region 帳密碼檢查

            var db = getDB0();
            //var get_secretary = db.Community.Where(x => x.account == model.account && x.passwd == model.password);
            SignInStatus         result;
            ApplicationUser      item;
            IEnumerable <string> get_user_roles_id;

            result = await SignInManager.PasswordSignInAsync(model.account, model.password, model.rememberme, shouldLockout : false);

            if (result == SignInStatus.Failure)
            {
                getLoginResult.result  = false;
                getLoginResult.message = Resources.Res.Login_Err_Password;
                return(defJSON(getLoginResult));
            }

            getLoginResult.result = true;
            item = await userManager.FindByNameAsync(model.account);

            get_user_roles_id = item.Roles.Select(x => x.RoleId);


            ApplicationDbContext context = ApplicationDbContext.Create();
            var roleManage          = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context));
            var get_user_roles_name = roleManage.Roles.Where(x => get_user_roles_id.Contains(x.Id)).Select(x => x.Name);
            getLoginResult.url = Url.Content("~/Active/CommunityNews");
            if (get_user_roles_name.Contains("Secretary"))
            {
                Response.Cookies.Add(new HttpCookie(CommWebSetup.Cookie_UserName, item.UserName));
            }
            Response.Cookies.Add(new HttpCookie(CommWebSetup.Cookie_LastLogin, DateTime.Now.ToString("yyyy-MM-dd")));
            #endregion

            //語系使用
            HttpCookie WebLang = Request.Cookies[CommWebSetup.WebCookiesId + ".Lang"];
            WebLang.Value    = model.lang;
            WebLang.HttpOnly = true;//避免被js隨意抓取cookie內容
            WebLang.SameSite = SameSiteMode.Lax;
            if (Request.IsSecureConnection)
            {
                WebLang.Secure = true;
            }
            Response.Cookies.Add(WebLang);

            try
            {
                var item_department = await db.Department.FindAsync(item.department_id);

                Response.Cookies.Add(new HttpCookie(CommWebSetup.Cookie_DepartmentId, item.department_id.ToString()));

                Response.Cookies.Add(new HttpCookie("user_login", Server.UrlEncode(EncryptString.desEncryptBase64("N"))));
                var item_lang = db.i_Lang
                                .Where(x => x.lang == WebLang.Value)
                                .Select(x => new { x.area })
                                .Single();

                ViewData["lang"] = item_lang.area;
                db.Dispose();
            }
            catch (Exception ex)
            {
                getLoginResult.result  = false;
                getLoginResult.message = ex.Message;
                return(defJSON(getLoginResult));
            }

            return(defJSON(getLoginResult));
        }
Exemplo n.º 28
0
 public ValidateResponseException(String message, ValidateResponse validateResponse) : base(message)
 {
     this.validateResponse = validateResponse;
 }
Exemplo n.º 29
0
        public static ValidateResponse ValidateRelationships(ServiceKey key)
        {
            var response = new ValidateResponse(true, key)
            {
                Errors = new List <IValidationError>()
            };
            var serviceName = ServiceDefinition.Get(key.Id).Name;

            try
            {
                var svcRelationships = Get(key);
                //got applicable relations
                var svcRel = svcRelationships.Select(def => def.GetDefinition(key)).Where(pd => pd != null).ToList();
                if (svcRel?.Count > 0)
                {
                    response.Errors.AddRange(from rel in svcRel
                                             where Convert.ToInt32(rel.Minimum) > 0
                                             where !(key.Relationships.Any(x => x.Key == rel.Name))
                                             select new ValidationError(string.Format("Required Related {0} is missing on service {1}", rel.Name, serviceName), ValidationError.RELATIONSHIP, key.GetIdentifier(null), ValidationError.MISSING, rel.Name + " is missing.", rel.Name));
                }
                if (key.Relationships != null)
                {
                    foreach (var pair in key.Relationships)
                    {
                        var relExists = svcRel.Any(x => x.Name == pair.Key);
                        if (!relExists)
                        {
                            response.AddError(string.Format("{0} is an unknown relationship for service {1}.", pair.Key,
                                                            serviceName), ValidationError.RELATIONSHIP, key.GetIdentifier(null), ValidationError.UNKNOWN, pair.Key + " is unknown for this service.", null);
                        }
                        else
                        {
                            var rel = svcRel.Find(x => x.Name == pair.Key);

                            if (key.Relationships[pair.Key].Count() < Convert.ToInt32(rel.Minimum))
                            {
                                response.AddError(
                                    string.Format(
                                        "Service relationship {0} for Service {1} does not meet the minimum of {2}.",
                                        pair.Key,
                                        serviceName, rel.Minimum), ValidationError.RELATIONSHIP, key.GetIdentifier(null), ValidationError.MINIMUM, pair.Value.Count + "<" + rel.Minimum);
                            }
                            if (key.Relationships[pair.Key].Count() > Convert.ToInt32(rel.Maximum) && Convert.ToInt32(rel.Maximum) != -1)
                            {
                                response.AddError(
                                    string.Format("Service relationship {0} for Service {1} exceeds the maximum of {2}.",
                                                  pair.Key, serviceName, rel.Maximum), ValidationError.RELATIONSHIP, key.GetIdentifier(null), ValidationError.MAXIMUM, pair.Value.Count + ">" + rel.Maximum, rel.Name);
                            }
                            foreach (var k in pair.Value.Where(k => !rel.Services.Contains(k.Id)))
                            {
                                response.AddError(
                                    string.Format(
                                        "Service relationship {0} for Service {1} does not support service of type {2}.",
                                        pair.Key, serviceName, ServiceDefinition.Get(k.Id).Name), ValidationError.RELATIONSHIP, k.GetIdentifier(null), ValidationError.INVALID_VALUE, k.Id.ToString(), rel.Name);
                            }
                        }
                    }
                }
                if (response.Errors.Count() > 0)
                {
                    response.IsValid = false;
                }
            }
            catch (Exception e)
            {
                response.AddError(e.Message, ValidationError.SERVICE, key.GetIdentifier(null), ValidationError.MISSING_CONFIG, e.Message);
                response.IsValid = false;
                return(response);
            }

            return(response);
        }
Exemplo n.º 30
0
        public async Task <string> ajax_Login(LoginViewModel model)
        {
            var userManager = UserManager;

            LoginResult getLoginResult = new LoginResult();

            //if (!ModelState.IsValid)
            //{
            //    getLoginResult.result = false;
            //    getLoginResult.message = "資訊不完整";
            //    return defJSON(getLoginResult);
            //}

            #region 驗證碼檢查程序

#if DEBUG
            getLoginResult.vildate = true;
#else
            //if (string.IsNullOrEmpty(Session["CheckCode"].ToString()))
            //{
            //    Session["CheckCode"] = Guid.NewGuid();
            //    getLoginResult.result = false;
            //    getLoginResult.message = Resources.Res.Log_Err_ImgValideNotEquel;
            //    return defJSON(getLoginResult);
            //}

            //getLoginResult.vildate = Session["CheckCode"].Equals(model.validate) ? true : false;
            ValidateResponse Validate = ValidateCaptcha(model.validate, "6LexIhoTAAAAAL-SrVm8_fYcL7pTnovF4T7GozRx");//正式:6LexIhoTAAAAAL-SrVm8_fYcL7pTnovF4T7GozRx,Demo:6LfOXBcTAAAAAOqEElEieoCCTQmHAmtRfnqSS141
            getLoginResult.vildate = Validate.Success;
#endif
            if (!getLoginResult.vildate)
            {
                //Session["CheckCode"] = Guid.NewGuid(); //只要有錯先隨意產生唯一碼 以防暴力破解,新的CheckCode會在Validate產生。
                getLoginResult.result  = false;
                getLoginResult.message = Resources.Res.Log_Err_googleValideNotEquel;
                return(defJSON(getLoginResult));
            }
            #endregion

            #region 帳密碼檢查

            var result = await SignInManager.PasswordSignInAsync(model.account, model.password, model.rememberme, shouldLockout : false);

            if (result == SignInStatus.Failure)
            {
                getLoginResult.result  = false;
                getLoginResult.message = Resources.Res.Login_Err_Password;
                return(defJSON(getLoginResult));
            }

            getLoginResult.result = true;
            var item = await userManager.FindByNameAsync(model.account);

            if (isTablet)
            {
                getLoginResult.url = Url.Content(CommWebSetup.ManageDefCTR);  //是行動裝置
            }
            else
            {
                //不是行動裝置
                var get_user_roles_id = item.Roles.Select(x => x.RoleId);

                ApplicationDbContext context = ApplicationDbContext.Create();
                var roleManage          = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context));
                var get_user_roles_name = roleManage.Roles.Where(x => get_user_roles_id.Contains(x.Id)).Select(x => x.Name);

                if (get_user_roles_name.Contains("Admins") || get_user_roles_name.Contains("Managers"))
                {
                    getLoginResult.url = Url.Content(CommWebSetup.ManageDefCTR);
                }
                else
                {
                    getLoginResult.url = Url.Content("~/Active/Sales/PersonalInfo");
                }
            }

            Response.Cookies.Add(new HttpCookie(CommWebSetup.Cookie_UserName, item.UserName));
            Response.Cookies.Add(new HttpCookie(CommWebSetup.Cookie_LastLogin, DateTime.Now.ToString("yyyy-MM-dd")));
            #endregion

            //語系使用
            HttpCookie WebLang = Request.Cookies[CommWebSetup.WebCookiesId + ".Lang"];
            //WebLang.Value = model.lang;
            Response.Cookies.Add(WebLang);

            try
            {
                var db = getDB0();

                var item_department = await db.Department.FindAsync(item.department_id);

                Response.Cookies.Add(new HttpCookie(CommWebSetup.Cookie_DepartmentId, item.department_id.ToString()));
                //Response.Cookies.Add(new HttpCookie(CommWebSetup.Cookie_DepartmentName, item_department.department_name));
                Response.Cookies.Add(new HttpCookie("user_login", Server.UrlEncode(EncryptString.desEncryptBase64("N"))));
                var item_lang = db.i_Lang
                                .Where(x => x.lang == WebLang.Value)
                                .Select(x => new { x.area })
                                .Single();

                ViewData["lang"] = item_lang.area;
                //Response.Cookies.Add(new HttpCookie(CommWebSetup.WebCookiesId + ".IsAuthorized", "OK"));//CKFinder
                Session["IsAuthorized"] = true;//ckfinder用
                db.Dispose();
            }
            catch (Exception ex)
            {
                getLoginResult.result  = false;
                getLoginResult.message = ex.Message;
                return(defJSON(getLoginResult));
            }

            return(defJSON(getLoginResult));
        }
Exemplo n.º 31
0
        public async Task <string> ajax_NewLogin(LoginViewModel model)
        {
            var         userManager    = UserManager;
            LoginResult getLoginResult = new LoginResult();

            #region 驗證碼檢查程序

#if DEBUG
            getLoginResult.vildate = true;
#else
            #region Google驗證
            if (!ModelState.IsValid)
            {
                getLoginResult.result  = false;
                getLoginResult.message = Resources.Res.Login_Err_Normal;
                return(defJSON(getLoginResult));
            }
            ValidateResponse Validate = ValidateCaptcha(model.validate);
            getLoginResult.vildate = Validate.Success;
            #endregion
#endif
            if (!getLoginResult.vildate)
            {
                //Session["CheckCode"] = Guid.NewGuid();//只要有錯先隨意產生唯一碼 以防暴力破解,新的CheckCode會在Validate產生。
                getLoginResult.result  = false;
                getLoginResult.message = Resources.Res.Log_Err_googleValideNotEquel;
                return(defJSON(getLoginResult));
            }
            #endregion

            try
            {
                #region 帳密碼檢查

                using (var db0 = getDB0())
                {
                    ApplicationUser      get_user;
                    IEnumerable <string> get_user_roles_name;

                    //string PW_Hash = UserManager.PasswordHasher.HashPassword(model.password);
                    get_user = await userManager.FindByNameAsync(model.account);

                    if (get_user == null)
                    {
                        getLoginResult.result  = false;
                        getLoginResult.message = Resources.Res.Login_Err_Password;
                        return(defJSON(getLoginResult));
                    }
                    else
                    {
                        var result = UserManager.PasswordHasher.VerifyHashedPassword(get_user.PasswordHash, model.password);
                        if (result != PasswordVerificationResult.Success)
                        {
                            getLoginResult.result  = false;
                            getLoginResult.message = Resources.Res.Login_Err_Password;
                            return(defJSON(getLoginResult));
                        }
                    }

                    getLoginResult.result = true;
                    get_user_roles_name   = db0.AspNetUsers.FirstOrDefault(x => x.Id == get_user.Id).AspNetRoles.Select(x => x.Name);
                    //本專案目前一個帳號只對映一個role 以first role為主

                    if (get_user != null)
                    {
                        #region 前台_會員登入用cookie

                        string userData                  = get_user_roles_name.FirstOrDefault();
                        string encode_userid             = Server.UrlEncode(EncryptString.desEncryptBase64(get_user.Id));//userid 加密
                        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, encode_userid, DateTime.Now, DateTime.Now.AddMinutes(300), false, userData, FormsAuthentication.FormsCookiePath);

                        string encTicket = FormsAuthentication.Encrypt(ticket);
                        Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));

                        var cookie_loginid = new HttpCookie(CommWebSetup.LoginId, Server.UrlEncode(EncryptString.desEncryptBase64(get_user.UserName)));
                        cookie_loginid.HttpOnly = true;
                        cookie_loginid.SameSite = SameSiteMode.Lax;
                        if (Request.IsSecureConnection)
                        {
                            cookie_loginid.Secure = true;
                        }
                        Response.Cookies.Add(cookie_loginid);

                        //LoginType //N:管理者登錄 Y:一般會員登錄
                        var cookie_login_type = new HttpCookie(CommWebSetup.LoginType, Server.UrlEncode(EncryptString.desEncryptBase64("N")));
                        cookie_login_type.HttpOnly = true;
                        cookie_login_type.SameSite = SameSiteMode.Lax;
                        if (Request.IsSecureConnection)
                        {
                            cookie_login_type.Secure = true;
                        }
                        Response.Cookies.Add(cookie_login_type);

                        #endregion
                        #region 後台_會員登入用cookie
                        Session["CheckCode"] = "jcin";

                        #endregion

                        getLoginResult.result = true;
                        string result_url = Url.Content(CommWebSetup.ManageDefCTR);

                        getLoginResult.url = result_url;
                        return(defJSON(getLoginResult));
                    }
                    else
                    {
                        getLoginResult.result  = false;
                        getLoginResult.message = Resources.Res.Login_Err_Password;//帳號或密碼錯誤 請重新輸入
                        return(defJSON(getLoginResult));
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                getLoginResult.result  = false;
                getLoginResult.message = ex.Message;
                return(defJSON(getLoginResult));
            }
        }