Change username in MVC 5 [closed] - identity

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am using ASP.NET MVC5 and Identity 2.0 (beta).
It is possible for users to change the username?
I am trying using UserManager.UpdateAsync method throws an exception.
Regrads,
Fran.

Yes it is possible using the UpdateAsync method but you need to ensure that you update both the email and username fields.
var user = userManager.FindById(userId);
user.Email = email;
user.UserName = email;
var updateResult = await userManager.UpdateAsync(user);
This method works successfully for me

This works for me:
public async Task<ActionResult> ChangeUsername(string value)
{
if (UserManager.Users.Where(x => x.UserName == value).FirstOrDefault() == null) //chk for dupes
{
var user = UserManager.FindById(User.Identity.GetUserId());
user.UserName = value;
var updateResult = await UserManager.UpdateAsync(user);
store.Context.SaveChanges();
await SignInAsync(user,true);//user is cached until logout so do this to clear cache
return Content("true");
}
throw new HttpException(500, "Please select a different username");
}

Maybe it's not so beautiful, but try this:
db.Database.ExecuteSqlCommand("update AspNetUsers set UserName=" + NewUserName + " where UserName = " + OldUserName);

Related

#1146 - Table 'crud_app.names' doesn't exist [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am following this tutorial here, crud app with node js and mysql.
My database, crud_app has a table named crud_table, and crud_table has got 3 columns, id, names, and date_added.
I am trying to make a SQL query using node js
async getAllData() {
try {
const response = await new Promise((resolve, reject) => {
const query = "SELECT * FROM names"
connection.query(query, (err, results) => {
if (err) { reject(new Error(err.message))}
resolve(results)
})
});
console.log(response);
return response;
} catch (error) {
console.log(error)
}
}
But I get this error
Error: ER_NO_SUCH_TABLE: Table 'crud_app.names' doesn't exist
And again I went to PHPMyAdmin to run this query in the console.
SELECT * FROM names
Output
It is claiming that the names column does not exist but you can clearly see the column here
Is there any way I can resolve this problem?
Your table name is crud_table and within your table you have the column names. You cant select all the date from a column by using SELECT * on the column,with SELECT you select data from your table in your case crud_table,so if you want all the names then try this "SELECT names FROM crud_table"

MySQL deadlock on account registration

I'm trying to implement a feature that detects whether or not an account has already signed up. Now when doing parallel requests I'm getting a deadlock. I think I understand why it is happening but I'm unsure on how to solve it.
Here's a simplified version of what I'm doing;
START TRANSACTION;
-- check if user has already signed up (returned rows > 0, throw error if so)
SELECT * FROM users WHERE email = 'example#site.com' FOR UPDATE;
-- user has not signed up yet.. create the account.
INSERT INTO users SET ...;
COMMIT;
Now this in itself works fine. However when two parallel request happen, a deadlock is made because the transaction will both create a FOR UPDATE lock, which is allowed because initially when there is no account signed up yet there are no rows to lock. Atleast, that's what I think is happening.. correct me if I'm wrong.
I'm curious on how I were to fix this, I still want to check whether not an account has registered already so I can show the user a message. Of course the email has a unique constraint but I do not want to rely on that because the auto increment index will increment, even when it violates the constraint.
Also I'm using typeorm, a sample of my code;
public async registerUser(email: string, password: string, displayName?: string) {
const connection = await getConnection();
connection.transaction(async (manager) => {
// First we need to make sure that this email isn't already registered. If
// it has been registered we can throw a simple UserError which will be
// caught by our error handler.
const hasAlreadyRegistered = await this.findUser(email, manager);
if (hasAlreadyRegistered) throw new UserError('Email has already been registered.');
// At last we can create the user, linking him to the previously created
// authentication strategy.
const user = new User();
user.email = email;
user.displayName = displayName || randomBytes(8).toString('hex');
user.strategies = [authentication];
await manager.save(user);
logger.silly('> Created user row.');
return user;
});
}
I have solved this by just checking for the constraint error in the end (per suggestion of #Shadow). It saves me a lot of hassle.
Code
try {
await manager.save(user);
} catch (err: any) {
// Check whether or not this entry violates an unique constraint.
if (err.code === 'ER_DUP_ENTRY') {
throw new UserError('Email has already been registered.');
} else throw err;
}

The property can not be used with this type of restriction error when trying to get Exchange contact by id using IndependentSoft EWS API

I am getting the following error when trying to retrieve a contact from Exchange server using IndependentSoft EWS API:
The property can not be used with this type of restriction.
Here is my code:
public Contact GetContact(string id){
var restriction = new IsEqualTo(PersonaPropertyPath.PersonaId, id);
var persona = _service.FindPeople(StandardFolder.Contacts, restriction).Personas.FirstOrDefault();
if (persona == null)
throw new NullReferenceException("Could not find contact in Exchange");
var contact = new Contact
{
Id = persona.PersonaId.ToString(),
Name = persona.DisplayName
};
if (persona.EmailAddress != null)
{
contact.Email = persona.EmailAddress.EmailAddress;
}
return contact;
}
The personaId like the EWSId of an Object is an identifier and isn't a validate search property. You really shouldn't need to search with it anyway you can get any information you after using the GetPersona Operation. If you really need to return the ContactType from the Gal you will need to search using the Email address from GetPersona if you trying to return a Contact from a Mailbox then GetPersona will give you that as part of the aggregate information.

What is the easiest way to add cities and countries of the world to an HTML5 form? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm creating a form, and I would like to allow the user to choose their country, and their city. What is the most effective way to do it?
For things like state and country, the possible number is reasonably small enough that you can build dropdowns for this without too much hassle. Here is a plugin for jQuery that has a "country picker" pre-made, and you can easily find the same for State on Google.
When you start talking about cities, there are a vastly large number of them. In my opinion, you're far better off using a simple textbox for this and letting the user fill it in themselves.
EDIT
Here is an example of building a country list from a database in MVC:
Country class (Model)
//This class represents a Country
public class Country
{
public int CountryID { get; set; }
public string CountryName {get; set; }
public Country(int countryID, string countryName)
{
this.CountryID = countryID;
this.CountryName = countryName;
}
}
Controller
List<Country> countries = new List<Country>(); //Create a list of Country objects
IEnumerable<SelectListItem> countryList; //List to hold the values for the dropdownlist
SqlConnection connection = new SqlConnection(connectionString); //build a connection with your connection string
connection.Open();
SqlCommand query = new SqlCommand("SELECT CountryID, CountryName FROM Country", connection); //query the table
query.CommandType = CommandType.Text;
SqlDataReader reader = query.ExecuteReader(); //execute the query
while (reader.Read()) //read out the results, set each result to a Country object
{
Country country = new Country(
Convert.ToInt32(reader["CountryID"]),
reader["CountryName"].ToString());
countries.Add(country); //add to the initial list
}
connection.Close();
//build the list of <SelectListItem>s to pass to the view
countryList = countries.Select(c => new System.Web.Mvc.SelectListItem
{
Text = c.CountryName,
Value = c.CountryID.ToString()
});
ViewBag.CountryList = countryList; //add the list to ViewBag
And the View
#Html.DropDownListFor(x => x.ID, new SelectList(ViewBag.CountryList, "Value", "Text"), new { #class = "formItem" })
This code hits your database for the list of countries and builds a List<Country> from the SqlDataReader. Then we turn these results into a List<SelectListItem> to pass into the view.
The result is a dropdown list that will always contain whatever records are in your database. If you add/remove items, the list will be representative of this.
The #Html.DropDownListFor(x => x.ID) binds the selected Value to the model's ID property, so you simply select this value on POST. (Note that your model will need to contain an ID property for this to work!
EDIT to emphasize the "fun" of making a city selector:
I really, really advise against trying to build a city selector. Check out the list of cities in Kansas (something I picked at random). I didn't bother to count these, but this is a pretty big list, and that alone is one state in one country in the world.
If you went with a database, you'd easily have thousands of records for the United States alone, and that only leaves you with 195 other countries to build data for.
Perhaps you can find a repository that already has this information available, but the amount of work required to make this happen seems prohibitive.

Change sha1 password mysql and Cakephp log in

I'm very new to CakePHP.
I've recently taken over a project that was built in CakePHP v 1.2.4.8284.
I'm trying to change the password for the login page.
There is only one user stored in a mysql database.
fields - id, username, password(varchar 40), nacl(char(6), firstname, lastname
In phpAdmin, I've tried changing the password while using the SHA1 function, but that doesn't work.
I've even tried creating a new user, but the new user information will not work either.
I've narrowed it down to the usercontroller in the following if statement:
if ($results && $results['User']['password'] == sha1($results['User']['nacl'] . sha1($this->data['User']['password'])))
It looks like the password in the database should have sha1(nacl field) + sha1(password field).
But it is all wrapped in a sha1.
I'm not sure how the encryption is working.
Any help would be appreciated.
Thanks in advance.
Here is the complete login function.
function login()
{
$this->set('error', false);
if ($this->Session->read('user'))
{
$this->redirect('/test-folder/');
} else {
$this->User->set($this->data);
if ($this->data) {
//$results = $this->User->findByUsername($this->data['User']['username']);
$results = $this->User->find('first', array(
'conditions' => array('username' => $this->data['User']['username'])
));
if ($results && $results['User']['password'] == sha1($results['User']['nacl'] . sha1($this->data['User']['password']))) {
$this->Session->write('user', $this->data['User']['username']);
$this->Session->write('admin', $results['User']['group']);
$this->redirect('/test-folder/');
} else {
$this->set('error', true);
}
}
}
}
Get the Security.salt in Config/core.php: 'securitysaltvalue'
Take a password 'yourplainpassword'
UPDATE user SET password = SHA1( CONCAT('securitysaltvalue', 'yourplainpassword')) WHERE id = 123
According to your code, you should be able to generate a new Password with these steps:
1) Generate a Password, for example "test123"
2) Get the id of the user you want to change the password for, for example 123
3) Execute this SQL in your phpMyAdmin (Replace my demo values!!!)
UPDATE user SET password = CONCAT( SHA1(nacl), SHA1("test123")) WHERE id = 123
And please make a complete DB dump on that table before any changes. And better yet, test on some development instance.
The answer from #StefanoDP works, but the table name is 'users', not 'user'. So the command should be:
UPDATE users SET password=SHA1(CONCAT('securitysaltvalue','yourplainpassword')) WHERE id=123;
Don't forget to add the semicolon at the end of the statement.