Display Email of the logged in user in MVC 5 - asp.net-mvc-5

Can someone please advise how do we display the EmailID of the logged-in user in a View. I am using ASP.NET MVC 5 identity.
Regards,
Ram

Assuming that you are using the user's email as the username then once the user has already been authenticated you can access the name from the User Principal Identity.Name
#if (Request.IsAuthenticated) {
<span>#User.Identity.Name</span>
}
That is the simple approach. If you did not use the email as the username then you will have to attach that info using claims and then you can use an extenion method to retrieve it. I had the reverse problem. I stored the email as the username and needed to get the logged-in user's Full Name to display. I then had to do what I described for you and had to add a custom DisplayName() extension for the IIdentity .

You can easily use the #inject feature call for injecting both UserManager and SignInManager (This feature available in .NET Core).
In your view add the following:
#inject SignInManager<YourUserIdentity> SignInManager
#inject UserManager<YourUserIdentity> UserManager
After the injection, you should be able to work with UserManager and SignInManager methods. For instance:
#if (SignInManager.IsSignedIn(User))
{
<a asp-area="" asp-controller="Manage" asp-action="Index" title="Manage">Hello #UserManager.GetUserName(User)</a>
}
else
{
}
Pay attention for passing the User object when you need to reference the current logged in user.
In your case, if you would like to get the logged in Email Address, you can use the following technique:
var loggedInUserName = #UserManager.GetUserName(User);
var loggedInEmail = await UserManager.GetEmailAsync(
UserManager.Users.FirstOrDefault(u => u.UserName == loggedInUserName)
);
Or just keep it inside a ViewBag as you like.
Hope this will be handy for anyone :)

Related

Is it possible to use OWIN to manage only the user login and logout?

I'd like to use authentication in MVC5 the same way I used in MVC4 FormsAuthenticaiton.SignIn(...), but I don't want to use Forms Auth. After OWIN was set as standard I read in a lot of places how it was safer and all that.
So what I mean by "the same way" is being able to just call a method and say the user is logged in or log the user out the same way, like FormsAuthentication.SignIn and FormsAuthentication.SignOut.
I don't want to customize OWIN's application user because I don't expose my POCO to my Web project and even less my DbContext (that's also heavily customized). All I want is to use OWIN, but just to manage the user session states (login, session, timeout, logout) I don't need, nor want OWIN's Roles, User and so forth.
I hope I was clear, if not please tell me what's unclear so I can try to improve it.
I appreciate any help, this thing is bugging me! :(
Well, after much code inspection and thanks to ReSharper's decompiler I was able to figure it out.
This is my working code:
public static IAuthenticationManager GetAuthenticationManager(this Controller controller)
{
return controller.HttpContext.GetOwinContext().Authentication;
}
public static void SignIn(this Controller controller, string username, string fullName, bool isPersistent = false)
{
var identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie, ClaimsIdentity.DefaultNameClaimType, null);
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, username, ClaimValueTypes.String));
identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, fullName, ClaimValueTypes.String));
identity.AddClaim(new Claim("LastLogin", DateTime.Now.ToString(CultureInfo.CurrentCulture)));
controller.GetAuthenticationManager().SignIn(new AuthenticationProperties { IsPersistent = isPersistent }, identity);
}
public static void SignOut(this Controller controller)
{
controller.GetAuthenticationManager().SignOut(DefaultAuthenticationTypes.ApplicationCookie);
}
What I did was create an extension class with these methods above and use it on my Controller, I just call the methods SignIn and SignOut. The "secret"/answer is:
Retrieve the IAuthenticationManager
Create a ClaimsIdentity with the login information I wanted
Sign in using the IAuthenticationManager and the ClaimsIdentity
That was it. =/

Logged in user can only access 1 page?

Using Orchard 1.6 Iv created a new role 'FactoryWorker'. When this user logs in from the front end I want them to be navigated to one page only.
OrchardLocal/System/ManufacturedProducts
I have set this page to be a print screen of the order details so the factory worker will know what products to get ready for ship out & they wont be able to navigate as no menu appears, but also need the other pages blocked incase the user decides to enter the URL of a page they arnt allowed access to.
This is the only page I want this particular user to be able to access(after they login), and I have added a logout button, which logs out the user and returns them to the home page.
So iv been looking through editing a role, with permissions and content etc...but this all seems to be applying to forms and content in general. where the user can access any content type etc...
So can someone advise me on how to do this?
thanks for any replies
UPDATE
I forgot to mention that this is not a content type, item or part I am talking about.
I have created my own controller & View & VM which is accessible from the dash board (using the AdminMenu, which brings the admin user to OrchardLocal/System/ManufacturedProducts)
I have looked at Orchard.ContentPermissions Feature but it only seems to allow me to 1)Grant permissions for others or 2)Grant permission for own content
any ideas?
You can use a Request Filter, (I do not know if it is the best way) :
FilterProvider – defines the filter applied to each request. Resembles the way default ASP.NET MVC action filters work with the difference that it’s not an attribute. All FilterProvider objects are injected into the request pipeline and are applied to all requests (so you need to check if the current request is suitable for your filter at the beginning of an appropriate method).
From : http://www.szmyd.com.pl/blog/most-useful-orchard-extension-points
So you could implement something like this
public class Filter : FilterProvider, IAuthorizationFilter {
private readonly IAuthenticationService _authenticationService;
public Filter(IAuthenticationService authenticationService) {
_authenticationService = authenticationService;
}
public void OnAuthorization(AuthorizationContext filterContext) {
//If route is the restricted one
if (filterContext.HttpContext.Request.Url.AbsoluteUri.Contains("OrchardLocal/System/ManufacturedProducts")) {
//Get the logged user
IUser loggedUser = _authenticationService.GetAuthenticatedUser();
if (loggedUser == null)
return filterContext.Result = new HttpUnauthorizedResult();
//Get the Roles
var roles = loggedUser.As<IUserRoles>().Roles;
if (!roles.Contains("FactoryUser")) {
//User is not authorized
return filterContext.Result = new HttpUnauthorizedResult();
}
}
}
}
Note: Untested code!
EDIT: Also you could invert the logic and check if the logged user has the role 'FactoryUser' and restrict its access to every page except the one they should see.
Your module can create a new permission (look at one of the permissions.cs files for examples), then create a role that has only that permission. Have your controller action check that permission (again, many examples found by finding usage of the permissions defined in one of the permissions.cs).
You can use the Content Permissions module. Using this module you can attach a content item permission part to a content type. This part allows you to choose which roles can see the content when you create it.

JSF Redirect page based on User role

I have two types of admin.
Super admin and normal admin.
Both start on the page admin.xhtml.
I want to forward super admin users to super-admin.xhtml and normal admin to normal-admin.xhtml.
How do I do this in JSF (I'm using Spring Security)?
I'm unfamiliar with JSF, but assuming it functions under the hood just like a Spring MVC JSP application, you can have your controller deliver a different page depending on the role(s) held by the user:
#RequestMapping("/admin.xhtml")
#PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_SUPERADMIN')")
public String getAdminPage(Modelmap model, Principal principal) {
Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
for (GrantedAuthority authority : authorities) {
if (authority.toString() == "ROLE_SUPERADMIN") { return "superadminpage"; }
}
//no need to check for admin privileges, since the annotation took care of that
//if you're not using annotations (or #PostAuthorize), you'd have to capture the
//'admin' role as well, and adjust the return statements accordingly.
return "adminpage";
}

SharePoint session persist across several users?

I have a custom web part that starts by getting a current user login name like this:
protected static string iAm = System.Web.HttpContext.Current.Request.ServerVariables["AUTH_USER"].Split("\\".ToCharArray())[1].ToLower().
Then it passes this string to a bbl class and fetches a user id:
`IDataReader _drInfo = cisf_BLL.bll_MyInfo.drGetMyInfo(iAm);
while (_drInfo.Read())
{
iUser_Ident = _drInfo.GetInt32(30);
}
`After that it passes the user id integer to another method that fetches user's training record:
_drUserTraining = bll_Training.drGet_required_training_records(iUser_Ident);
_drUserTrainingCompleted = bll_Training.drGet_completed_training_records(iUser_Ident);
This information is then displayed in a tab container with three tab such as "Overdue", "Required", and "Completed".
The problem I'm having is this: I'm logged into SharePoint collaboration site with my domain user name and all my training is displayed just fine. If my someone else then logs in to the SP Portal that user sees my training and not his, even though this user has logged in with his unique credential using a common access card, just as I.
Somehow some strange session seems to persist and I was hoping someone out here has encountered this anomaly.
Thanks in advance!
Risho
You are misusing static - a static property is stored once per web server process, not once per user.
Not an answer, but code improvement: there is much simplyer way to get current user name/id
SPUser user = Microsoft.SharePoint.[SPContext][1].Current.Web.CurrentUser;
user.ID;
user.Email;
user.Name
user.LoginName;
user.Grups;
....
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spuser_members.aspx

Accessing the user from a liferay portlet?

I'm attempting to develop a portlet for liferay.
How can I get access to the username and password (and other data liferay has) of the user that's currently logged in?
I'd also like to be able to execute some code when users change their password.
You can get the User ID by calling getRemoteUser() in the PortletRequest object. This is defined by JSR-168 therefore it's cross-portal compatible.
Once you have the ID you can fetch the additional informations by calling getUserById() (a Liferay specific service). This is something not covered by Portlet API specification, so it locks you to the Liferay.
Liferay Specific stuff, here is a code sample to be written in your Portlet Class to retrieve the User:
ThemeDisplay themeDisplay = (ThemeDisplay)portletRequest.getAttribute(WebKeys.THEME_DISPLAY);
User user = themeDisplay.getRealUser(); // it gives you the actual Logged in User
//you can also use
// User user = themeDisplay.getUser(); // this would fetch the User you are impersonating
long userId = user.getUserId();
String userName = user.getEmailAddress();
Alternatively;
long userId = themeDisplay.getRealUserId(); // themeDisplay.getUserId();
User user = UserLocalServiceUtil.getUser(userId);
Impersonate User:
Liferay has a concept that admins (or persons with the correct set of permissions) can impersonate a particular user of the portal. Through this they can see how the portal looks to that user.
For executing the code when user change their passwords:
One approach would be to create a hook plugin and overriding the services by extending the UserLocalServiceWrapper class. Then checking for the password change and executing your code inside the your custom class.
Hope this helps.
Or you can just use javascript:
Liferay.ThemeDisplay.getUserId()
There are many nice to haves in the Liferay namespace, take a look at the not so well documented API:
https://www.liferay.com/community/wiki/-/wiki/Main/Liferay+JavaScript+API
https://www.liferay.com/web/pankaj.kathiriya/blog/-/blogs/usage-of-liferay-js-object
Also, take a look at the web services available under localhost:8080/api/jsonws which you can invoke with a javascript call:
Liferay.Service(
'/user/get-user-by-id',
{
userId: 10199
},
function(obj) {
console.log(obj);
}
);
One simple and easy way to get the user in Liferay is PortalUtil.getUser function.
User user = PortalUtil.getUser(portletRequest);

Resources