Ejemplo n.º 1
0
        private async Task SendEmail(string to, string subject, string body)
        {
            try
            {
                using (SmtpClient client = new SmtpClient())
                {
                    using (MailMessage message = new MailMessage())
                    {
                        string userName = Settings.Provider.EmailAddress;
                        message.From = new MailAddress(userName, "Shopping App");
                        message.To.Add(new MailAddress(to));

                        message.IsBodyHtml = true;
                        message.Subject    = subject;
                        message.Body       = body;

                        await client.SendMailAsync(message);
                    }
                }
            }

            catch (Exception ex)
            {
                TracingSystem.TraceException("Email failed to send", ex);
            }
        }
Ejemplo n.º 2
0
        protected void Application_Error(object sender, EventArgs e)
        {
            Core.TracingSystem.TraceInformation("Inside Global");

            Exception exception = Server.GetLastError();

            Core.TracingSystem.TraceError(exception.ToString());

            // if the error is NOT http error, then stop handling it.
            if (!(exception is HttpException httpException))
            {
                return;
            }

            if (httpException.GetHttpCode() != 404)
            {
                TracingSystem.TraceException("Exception from [Global.Application_Error] method : ", httpException);
            }

            Response.Clear();
            Response.TrySkipIisCustomErrors = true;
            Server.ClearError();

            if (new HttpRequestWrapper(Request).IsAjaxRequest())
            {
                HandleExceptionInAjaxContext(exception);
            }
            else
            {
                HandleExceptionInNormalContext(httpException);
            }
        }
        public virtual void OnException(ExceptionContext filterContext)
        {
            if (filterContext.Exception == null)
            {
                return;
            }

            TracingSystem.TraceException(filterContext.Exception);

            string message = HandleHttpRequestValidationException(filterContext.Exception);

            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;

            if (filterContext.Exception is PermissionException)
            {
                filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.Unauthorized;
            }
            else
            {
                filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
            }

            filterContext.Result = new JsonResult {
                Data = message
            };
        }
Ejemplo n.º 4
0
 public async Task Handle(RequestAdded args)
 {
     try {
         string deviceId     = args.DeviceId;//This is an assumption here
         var    notification = CreateAndroidPartnerAppNotification(deviceId);
         // this statment is executed, and the text log file will contains this line
         TracingSystem.TraceInformation("Before Send Google Notification");
         await SendersFacade.PartnerSender.SendAsync(notification);
     } catch (Exception ex) {
         TracingSystem.TraceException(ex);
     }
 }
Ejemplo n.º 5
0
            private static async Task <ClaimsIdentity> GetFacebook(string accessToken)
            {
                try
                {
                    string verifyTokenEndPoint = string.Format("https://graph.facebook.com/me?access_token={0}", accessToken);
                    string verifyAppEndPoint   = string.Format("https://graph.facebook.com/app?access_token={0}", accessToken);

                    HttpClient client = new HttpClient();

                    Uri uri = new Uri(verifyTokenEndPoint);
                    HttpResponseMessage response = await client.GetAsync(uri);

                    ClaimsIdentity identity = null;

                    if (!response.IsSuccessStatusCode)
                    {
                        return(null);
                    }

                    string content = await response.Content.ReadAsStringAsync();

                    dynamic iObj = (JObject)JsonConvert.DeserializeObject(content);

                    identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);

                    uri      = new Uri(verifyAppEndPoint);
                    response = await client.GetAsync(uri);

                    content = await response.Content.ReadAsStringAsync();

                    dynamic appObj = (JObject)JsonConvert.DeserializeObject(content);
                    if (appObj["id"] != Settings.Provider.Facebook_AppId)
                    {
                        return(null);
                    }

                    identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, iObj["id"].ToString(), ClaimValueTypes.String, "Facebook", "Facebook"));
                    return(identity);
                }
                catch (Exception ex)
                {
                    TracingSystem.TraceException(ex);
                    return(null);
                }
            }
Ejemplo n.º 6
0
        protected override void OnException(ExceptionContext filterContext)
        {
            if (filterContext.ExceptionHandled)
            {
                return;
            }

            filterContext.ExceptionHandled = true;
            Exception exception = filterContext.Exception;

            // get the ControllerName and the ActionName where the exception has raised.
            string controller = filterContext.RouteData.Values["controller"].ToString();
            string action     = filterContext.RouteData.Values["action"].ToString();

            // Log the error, which occurred.
            TracingSystem.TraceException(filterContext.Exception);

            HandleErrorInfo model = new HandleErrorInfo(exception, controller, action);

            filterContext.Result = View("~/Views/Shared/Error.cshtml", model);
        }
Ejemplo n.º 7
0
        public override void OnException(HttpActionExecutedContext context)
        {
            TracingSystem.TraceException(context.ActionContext.Request.RequestUri.AbsolutePath, context.Exception);

            if (context.Exception is BusinessRuleException)
            {
                BusinessRuleException ex = context.Exception as BusinessRuleException;
                throw new HttpResponseException(context.Request.CreateErrorResponse(HttpStatusCode.BadRequest, context.Exception.Message));
            }

            if (context.Exception is ValidationException)
            {
                ValidationException ex = context.Exception as ValidationException;
                throw new HttpResponseException(context.Request.CreateErrorResponse(HttpStatusCode.BadRequest, context.Exception.Message));
            }

            if (context.Exception is ArgumentNullException)
            {
                throw new HttpResponseException(context.Request.CreateErrorResponse(HttpStatusCode.BadRequest, context.Exception.Message));
            }

            throw new HttpResponseException(context.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, context.Exception.InnerException?.Message ?? context.Exception.Message));
        }
Ejemplo n.º 8
0
            private static async Task <ClaimsIdentity> GetGoogle(string accessToken)
            {
                try
                {
                    string verifyTokenEndPoint = string.Format("https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={0}", accessToken);

                    HttpClient          client   = new HttpClient();
                    Uri                 uri      = new Uri(verifyTokenEndPoint);
                    HttpResponseMessage response = await client.GetAsync(uri);

                    ClaimsIdentity identity = null;

                    if (!response.IsSuccessStatusCode)
                    {
                        return(null);
                    }

                    string content = await response.Content.ReadAsStringAsync();

                    dynamic iObj = (JObject)JsonConvert.DeserializeObject(content);

                    if (iObj["issued_to"] != Settings.Provider.Goggle_ClientId)
                    {
                        return(null);
                    }

                    identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);
                    identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, iObj["user_id"].ToString(), ClaimValueTypes.String, "Google", "Google"));
                    return(identity);
                }
                catch (Exception ex)
                {
                    TracingSystem.TraceException(ex);
                    return(null);
                }
            }
Ejemplo n.º 9
0
        public async Task <IHttpActionResult> RegisterExternal(RegisterExternalBindingModel model)
        {
            try
            {
                ExternalLoginData externalLogin = await ExternalLoginData.FromToken(model.Provider, model.Token);

                if (externalLogin == null)
                {
                    throw new Exception("externalLogin can not be found, externalLogin is null");
                }

                if (externalLogin.LoginProvider != model.Provider)
                {
                    Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
                    throw new Exception("Provider Conflicts, the Provider which send by user is not the same of the externalLogin's provider");
                }

                User user = await UserService.Obj.FindByEmailAsync(model.Email);

                bool registered = user != null;
                if (!registered)
                {
                    user = new User(model.Name, model.Email);
                    user.UpdateRoles(RoleService.Obj.GetByNames(RoleNames.UserRole));
                    user.PerformConfirmEmail();

                    user = await UserService.Obj.CreateExternalUserAsync(user, new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey));
                }

                // Authenticate
                ClaimsIdentity identity = await UserService.Obj.CreateIdentityAsync(user, OAuthDefaults.AuthenticationType);

                IEnumerable <Claim> claims = externalLogin.GetClaims();
                identity.AddClaims(claims);
                Authentication.SignIn(identity);

                ClaimsIdentity oAuthIdentity = new ClaimsIdentity(Startup.OAuthOptions.AuthenticationType);

                oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
                oAuthIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()));

                oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, RoleNames.UserRole));

                AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties());

                DateTime currentUtc = DateTime.UtcNow;
                ticket.Properties.IssuedUtc  = currentUtc;
                ticket.Properties.ExpiresUtc = currentUtc.Add(Startup.OAuthOptions.AccessTokenExpireTimeSpan);

                string accessToken  = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);
                string refreshToken = Startup.OAuthOptions.RefreshTokenFormat.Protect(ticket);
                Request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);

                var token = new
                {
                    userName      = user.UserName,
                    userId        = user.Id,
                    access_token  = accessToken,
                    refresh_token = refreshToken,
                    token_type    = "bearer",
                    expires_in    = Startup.OAuthOptions.AccessTokenExpireTimeSpan.TotalSeconds.ToString(),
                    issued        = currentUtc.ToString("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'"),
                    expires       = currentUtc.Add(Startup.OAuthOptions.AccessTokenExpireTimeSpan).ToString("ddd, dd MMM yyyy HH:mm:ss 'GMT'")
                };

                return(Ok(token));
            }
            catch (Exception ex)
            {
                TracingSystem.TraceException(ex);
                return(InternalServerError());
            }
        }