* avatar, username, city from Google profile

* refactoring
This commit is contained in:
Paul Schneider 2014-12-20 02:11:51 +01:00
commit c7f81699a4
55 changed files with 706 additions and 351 deletions

View file

@ -21,7 +21,13 @@ namespace Yavsc.Controllers
WebConfigurationManager.AppSettings ["RegistrationMessage"];
string avatarDir = "~/avatars";
/// <summary>
/// Gets or sets the avatar dir.
/// This value is past to <c>Server.MapPath</c>,
/// it should start with </c>~/</c>, and we assume it
/// to be relative to the application path.
/// </summary>
/// <value>The avatar dir.</value>
public string AvatarDir {
get { return avatarDir; }
set { avatarDir = value; }
@ -159,6 +165,17 @@ namespace Yavsc.Controllers
return View();
}
[Authorize]
public ActionResult Unregister(bool confirmed=false)
{
if (!confirmed)
return View ();
Membership.DeleteUser (
Membership.GetUser ().UserName);
return RedirectToAction ("Index","Home");
}
[Authorize]
[HttpPost]
public ActionResult ChangePassword (ChangePasswordModel model)
@ -173,6 +190,7 @@ namespace Yavsc.Controllers
if (users.Count > 0) {
MembershipUser user = Membership.GetUser (model.Username,true);
changePasswordSucceeded = user.ChangePassword (model.OldPassword, model.NewPassword);
} else {
changePasswordSucceeded = false;
@ -213,13 +231,15 @@ namespace Yavsc.Controllers
if (AvatarFile != null) {
if (AvatarFile.ContentType == "image/png") {
// byte[] img = new byte[AvatarFile.ContentLength];
// AvatarFile.InputStream.Read (img, 0, AvatarFile.ContentLength);
// model.Avatar = img;
string avdir=Server.MapPath (AvatarDir);
string avpath=Path.Combine(avdir,username+".png");
AvatarFile.SaveAs (avpath);
string avuri = avpath.Substring(
AppDomain.CurrentDomain.BaseDirectory.Length);
avuri = avuri.Replace (" ", "+");
avuri = Request.Url.Scheme + "://" + Request.Url.Authority + "/" + avuri;
HttpContext.Profile.SetPropertyValue ("avatar", avuri );
HttpContext.Profile.Save ();
} else
ModelState.AddModelError ("Avatar",
string.Format ("Image type {0} is not supported (suported formats : {1})",

View file

@ -11,6 +11,12 @@ namespace Yavsc.ApiControllers
// TODO should mostly be an API Controller
public class BasketController : ApiController
{
protected WorkFlowManager wfmgr = null;
protected override void Initialize (System.Web.Http.Controllers.HttpControllerContext controllerContext)
{
base.Initialize (controllerContext);
wfmgr = new WorkFlowManager ();
}
/// <summary>
/// Validates the order.
///
@ -42,7 +48,7 @@ namespace Yavsc.ApiControllers
[Authorize]
public Estimate[] YourEstimates()
{
return WorkFlowManager.GetEstimates (
return wfmgr.GetEstimates (
Membership.GetUser().UserName);
}

View file

@ -18,6 +18,7 @@ using Yavsc.Model;
using Yavsc.Model.Blogs;
using Yavsc.ApiControllers;
using Yavsc.Model.RolesAndMembers;
using System.Net;
namespace Yavsc.Controllers
{
@ -234,12 +235,19 @@ namespace Yavsc.Controllers
[AcceptVerbs (HttpVerbs.Get)]
public ActionResult Avatar (string user)
{
string avpath = Path.Combine (
Server.MapPath (AvatarDir), user + ".png");
FileInfo fia = new FileInfo (avpath);
if (!fia.Exists)
fia = new FileInfo (Server.MapPath (defaultAvatar));
return File (fia.OpenRead (), defaultAvatarMimetype);
ProfileBase pr = ProfileBase.Create (user);
string avpath = (string) pr.GetPropertyValue ("avatar");
if (avpath == null) {
FileInfo fia = new FileInfo (Server.MapPath (defaultAvatar));
return File (fia.OpenRead (), defaultAvatarMimetype);
}
WebRequest wr = WebRequest.Create(avpath);
using (WebResponse resp = wr.GetResponse ()) {
using (Stream str = resp.GetResponseStream ()) {
return File (str, resp.ContentType);
}
}
}
/// <summary>

View file

@ -29,6 +29,14 @@ namespace Yavsc.ApiControllers
public class FrontOfficeController : ApiController
{
protected WorkFlowManager wfmgr = null;
protected override void Initialize (System.Web.Http.Controllers.HttpControllerContext controllerContext)
{
base.Initialize (controllerContext);
wfmgr = new WorkFlowManager ();
}
[AcceptVerbs("GET")]
public Catalog Catalog ()
{
@ -87,7 +95,7 @@ namespace Yavsc.ApiControllers
/// <param name="estid">Estid.</param>
public Estimate GetEstimate (long Id)
{
Estimate est = WorkFlowManager.ContentProvider.GetEstimate (Id);
Estimate est = wfmgr.ContentProvider.GetEstimate (Id);
return est;
}
@ -107,7 +115,7 @@ namespace Yavsc.ApiControllers
private string getEstimTex(long estimid)
{
Yavsc.templates.Estim tmpe = new Yavsc.templates.Estim();
Estimate e = WorkFlowManager.GetEstimate (estimid);
Estimate e = wfmgr.GetEstimate (estimid);
tmpe.Session = new Dictionary<string,object>();
tmpe.Session.Add ("estim", e);
@ -132,7 +140,7 @@ namespace Yavsc.ApiControllers
/// <param name="estimid">Estimid.</param>
public HttpResponseMessage GetEstimPdf(long estimid)
{
Estimate estim = WorkFlowManager.GetEstimate (estimid);
Estimate estim = wfmgr.GetEstimate (estimid);
//TODO better with pro.IsBankable && cli.IsBillable
return new HttpResponseMessage () {

View file

@ -8,6 +8,7 @@ using System.Text.RegularExpressions;
using System.IO;
using Yavsc.Controllers;
using System.Collections.Generic;
using Yavsc.Model;
using Yavsc.Model.WorkFlow;
using WorkFlowProvider;
using System.Web.Security;
@ -21,14 +22,20 @@ namespace Yavsc.Controllers
/// </summary>
public class FrontOfficeController : Controller
{
/*
protected WorkFlowManager wfmgr = null;
protected override void Initialize (System.Web.Routing.RequestContext requestContext)
{
base.Initialize (requestContext);
wfmgr = new WorkFlowManager ();
}
*/
[Authorize]
public ActionResult Estimates ()
{
string username = Membership.GetUser ().UserName;
return View(WorkFlowManager.GetEstimates (username));
return View(wfmgr.GetEstimates (username));
}
[Authorize]
@ -38,7 +45,7 @@ namespace Yavsc.Controllers
ViewData ["WABASEWF"] = ViewData ["WebApiBase"] + "/WorkFlow";
if (submit == null) {
if (model.Id > 0) {
Estimate f = WorkFlowManager.GetEstimate (model.Id);
Estimate f = wfmgr.GetEstimate (model.Id);
if (f == null) {
ModelState.AddModelError ("Id", "Wrong Id");
return View (model);
@ -64,12 +71,12 @@ namespace Yavsc.Controllers
throw new UnauthorizedAccessException ("You're not allowed to modify this estimate");
if (model.Id == 0)
model = WorkFlowManager.CreateEstimate (
model = wfmgr.CreateEstimate (
username,
model.Client, model.Title, model.Description);
else {
WorkFlowManager.UpdateEstimate (model);
model = WorkFlowManager.GetEstimate (model.Id);
wfmgr.UpdateEstimate (model);
model = wfmgr.GetEstimate (model.Id);
}
}
}

View file

@ -12,27 +12,27 @@ using System.Net;
using System.IO;
using Yavsc.Model;
using Newtonsoft.Json;
using Yavsc.Model.Google;
using Yavsc.Model.RolesAndMembers;
using System.Web.Security;
using System.Web.Profile;
namespace Yavsc.Controllers
{
public class TokenResult {
public string access_token { get; set; }
public string id_token { get; set; }
public int expires_in { get; set; }
public string token_type { get; set ; }
public string refresh_token { get; set; }
}
public class GoogleController : Controller
{
private string API_KEY="AIzaSyBV_LQHb22nGgjNvFzZwnQHjao3Q7IewRw";
// private string API_KEY="AIzaSyBV_LQHb22nGgjNvFzZwnQHjao3Q7IewRw";
private string getPeopleUri = "https://www.googleapis.com/plus/v1/people";
private string CLIENT_ID="325408689282-6bekh7p3guj4k0f3301a6frf025cnrk1.apps.googleusercontent.com";
private string CLIENT_SECRET="MaxYcvJJCs2gDGvaELZbzwfL";
string [] SCOPES = {
"openid" ,
"profile",
"email"
} ;
@ -40,43 +40,37 @@ namespace Yavsc.Controllers
string tokenUri = "https://accounts.google.com/o/oauth2/token";
string authUri = "https://accounts.google.com/o/oauth2/auth";
public void Login()
public void Login(string returnUrl)
{
if (string.IsNullOrWhiteSpace (returnUrl))
returnUrl = "/";
Random rand = new Random ();
string state = "security_token"+rand.Next (100000).ToString()+rand.Next (100000).ToString();
Session ["state"] = state;
Session ["returnUrl"] = returnUrl;
string redirectUri = Request.Url.Scheme + "://" + Request.Url.Authority + "/Google/Auth";
string prms = String.Format("response_type=code&" +
"client_id={0}&" +
"redirect_uri={1}&" +
"scope={2}&" +
"state={3}&" +
"access_type=offline&" +
"include_granted_scopes=false",
CLIENT_ID,
redirectUri,
string.Join("%20",SCOPES),
state
);
string prms = String.Format("response_type=code&client_id={0}&redirect_uri={1}&scope={2}&state={3}&access_type=offline&include_granted_scopes=false",
CLIENT_ID, redirectUri, string.Join("%20",SCOPES), state);
WebRequest wr = WebRequest.Create(authUri+"?"+prms);
wr.Method = "GET";
// Get the response.
try {
WebResponse response = wr.GetResponse();
string resQuery = response.ResponseUri.Query;
string cont = HttpUtility.ParseQueryString(resQuery)["continue"];
Response.Redirect (cont);
}
catch (WebException we) {
Response.Redirect(we.Response.ResponseUri.AbsoluteUri);
}
}
public void Auth() {
[HttpGet]
public ActionResult Auth()
{
string returnUrl = (string) Session ["returnUrl"];
string redirectUri = Request.Url.Scheme + "://" + Request.Url.Authority + "/Google/Auth";
string code = Request.Params ["code"];
string error = Request.Params ["error"];
@ -84,13 +78,13 @@ namespace Yavsc.Controllers
ViewData ["Message"] =
string.Format(LocalizedText.Google_error,
LocalizedText.ResourceManager.GetString(error));
return;
return View();
}
string state = Request.Params ["state"];
if (state!=null && string.Compare((string)Session ["state"],state)!=0) {
ViewData ["Message"] =
LocalizedText.ResourceManager.GetString("invalid request state");
return;
return View();
}
string postdata =
@ -112,17 +106,113 @@ namespace Yavsc.Controllers
};
using (WebResponse response = webreq.GetResponse ()) {
using (Stream responseStream = response.GetResponseStream ()) {
using (StreamReader readStream = new StreamReader (responseStream, Encoding.ASCII)) {
using (StreamReader readStream = new StreamReader (responseStream, Encoding.UTF8)) {
string responseStr = readStream.ReadToEnd ();
TokenResult res = JsonConvert.DeserializeObject<TokenResult>(responseStr);
AuthToken gat = JsonConvert.DeserializeObject<AuthToken>(responseStr);
Session ["GoogleAuthToken"] = gat;
SignIn regmod = new SignIn ();
HttpWebRequest webreppro = WebRequest.CreateHttp (getPeopleUri+"/me");
webreppro.ContentType = "application/http";
webreppro.Headers.Add (HttpRequestHeader.Authorization, gat.token_type + " " + gat.access_token);
webreppro.Method = "GET";
using (WebResponse proresp = webreppro.GetResponse ()) {
using (Stream prresponseStream = proresp.GetResponseStream ()) {
using (StreamReader readproresp = new StreamReader (prresponseStream, Encoding.UTF8)) {
string prresponseStr = readproresp.ReadToEnd ();
People me = JsonConvert.DeserializeObject<People> (prresponseStr);
// TODO use me.id to retreive an existing user
string accEmail = me.emails.Where (x => x.type == "account").First().value;
MembershipUserCollection mbrs = Membership.FindUsersByEmail (accEmail);
if (mbrs.Count == 1) {
// TODO check the google id
// just set this user as logged on
FormsAuthentication.SetAuthCookie (me.displayName, true);
Session ["returnUrl"] = null;
return Redirect (returnUrl);
}
// else create the account
regmod.Email = accEmail;
regmod.UserName = me.displayName;
Session ["me"] = me;
return Auth(regmod);
}
}
}
}
}
}
}
/// <summary>
/// Creates an account using the Google authentification.
/// </summary>
/// <param name="regmod">Regmod.</param>
[HttpPost]
public ActionResult Auth(SignIn regmod)
{
if (ModelState.IsValid) {
if (Membership.GetUser (regmod.UserName) != null) {
ModelState.AddModelError ("UserName", "This user name already is in use");
return View ();
}
string returnUrl = (string)Session ["returnUrl"];
AuthToken gat = (AuthToken)Session ["GoogleAuthToken"];
People me = (People)Session ["me"];
if (gat == null || me == null)
throw new InvalidDataException ();
Random rand = new Random ();
string passwd = rand.Next (100000).ToString () + rand.Next (100000).ToString ();
MembershipCreateStatus mcs;
Membership.CreateUser (
regmod.UserName,
passwd,
regmod.Email,
null,
null,
true,
out mcs);
switch (mcs) {
case MembershipCreateStatus.DuplicateEmail:
ModelState.AddModelError ("Email", "Cette adresse e-mail correspond " +
"à un compte utilisateur existant");
return View (regmod);
case MembershipCreateStatus.DuplicateUserName:
ModelState.AddModelError ("UserName", "Ce nom d'utilisateur est " +
"déjà enregistré");
return View (regmod);
case MembershipCreateStatus.Success:
Membership.ValidateUser (regmod.UserName, passwd);
FormsAuthentication.SetAuthCookie (regmod.UserName, true);
HttpContext.Profile.Initialize (regmod.UserName, true);
HttpContext.Profile.SetPropertyValue ("gtoken", gat.access_token);
HttpContext.Profile.SetPropertyValue ("Name", me.displayName);
// TODO use image
if (me.image != null) {
HttpContext.Profile.SetPropertyValue ("avatar", me.image.url);
}
if (me.placesLived != null) {
People.Place pplace = me.placesLived.Where (x => x.primary).First ();
if (pplace != null)
HttpContext.Profile.SetPropertyValue ("Address", pplace.value);
}
if (me.url != null)
HttpContext.Profile.SetPropertyValue ("WebSite", me.url);
HttpContext.Profile.Save ();
return Redirect (returnUrl);
}
ViewData ["returnUrl"] = returnUrl;
}
return View (regmod);
}
public void ChooseCalendar()
{
throw new NotImplementedException();
}
}
}

View file

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Yavsc.Model;
using System.Configuration;
namespace Yavsc.Controllers
{
public class ModuleController : Controller
{
protected override void Initialize (System.Web.Routing.RequestContext requestContext)
{
base.Initialize (requestContext);
ConfigurationManager.GetSection ("ymodules");
}
// List<IModule> modules = new List<IModule> ();
public ActionResult Index()
{
return View ();
}
}
}

View file

@ -15,7 +15,7 @@ namespace Yavsc.ApiControllers
public class WorkFlowController : ApiController
{
string adminRoleName="Admin";
protected WorkFlowManager wfmgr = null;
protected override void Initialize (HttpControllerContext controllerContext)
{
// TODO move it in a module initialization
@ -23,13 +23,14 @@ namespace Yavsc.ApiControllers
if (!Roles.RoleExists (adminRoleName)) {
Roles.CreateRole (adminRoleName);
}
wfmgr = new WorkFlowManager ();
}
[HttpGet]
[Authorize]
public Estimate CreateEstimate (string title,string client,string description)
{
return WorkFlowManager.CreateEstimate (
return wfmgr.CreateEstimate (
Membership.GetUser().UserName,client,title,description);
}
@ -37,7 +38,7 @@ namespace Yavsc.ApiControllers
[Authorize]
public void DropWritting(long wrid)
{
WorkFlowManager.DropWritting (wrid);
wfmgr.DropWritting (wrid);
}
@ -46,13 +47,13 @@ namespace Yavsc.ApiControllers
[Authorize]
public void DropEstimate(long estid)
{
WorkFlowManager.DropEstimate (estid);
wfmgr.DropEstimate (estid);
}
[HttpGet]
[Authorize]
public object Index()
{
{
// TODO inform user on its roles and alerts
string username = Membership.GetUser ().UserName;
return new { test=string.Format("Hello {0}!",username) };
@ -75,7 +76,7 @@ namespace Yavsc.ApiControllers
[ValidateAjax]
public HttpResponseMessage UpdateWritting([FromBody] Writting wr)
{
WorkFlowManager.UpdateWritting (wr);
wfmgr.UpdateWritting (wr);
return Request.CreateResponse (System.Net.HttpStatusCode.OK);
}
@ -95,7 +96,7 @@ namespace Yavsc.ApiControllers
}
try {
return Request.CreateResponse(System.Net.HttpStatusCode.OK,
WorkFlowManager.Write(estid, wr.Description,
wfmgr.Write(estid, wr.Description,
wr.UnitaryCost, wr.Count, wr.ProductReference));
}
catch (Exception ex) {