Problem: I want to create user in sitecore using Microsoft powershell script. I do not want to use powershell provided by sitecore.
I am able to create user using powershell script within the sitecore. But the requirement is to create new user in each environment using powershell scripts while doing setup.
A Sitecore user is a normal ASP.NET Membership user in the Sitecore core SQL database. (default but depend on your config). And in Microsoft PowerShell you can do a SQL query.
First create the user by using stored procedure aspnet_Membership_CreateUser and use as ApplicationName 'sitecore' and use the sitecore domain.
This SQL creates an valid Sitecore user:
declare #salt nvarchar(128)
declare #password varbinary(256)
declare #input varbinary(512)
declare #hash varchar(64)
-- Change these values (#salt should be Base64 encoded)
set #salt = N'eyhKDP858wdrYHbBmFoQ6DXzFE1FB+RDP4ULrpoZXt6f'
set #password = convert(varbinary(256),N'mypassword')
set #input = hashbytes('sha1',cast('' as xml).value('xs:base64Binary(sql:variable(''#salt''))','varbinary(256)') + #password)
set #hash = cast('' as xml).value('xs:base64Binary(xs:hexBinary(sql:variable(''#input'')))','varchar(64)')
-- #hash now contains a suitable password hash
-- Now create the user using the value of #salt as the salt, and the value of #hash as the password (with the #PasswordFormat set to 1)
DECLARE #return_value int,
#UserId uniqueidentifier
EXEC #return_value = [dbo].[aspnet_Membership_CreateUser]
#ApplicationName = N'sitecore',
#UserName = N'sitecore\startup',
#Password = #hash,
#PasswordSalt = #salt,
#Email = N'jan#test.com',
#PasswordQuestion = N'nope',
#PasswordAnswer = N'nope',
#IsApproved = 1,
#CurrentTimeUtc = '2017-03-03',
#CreateDate = '2017-03-03',
#UniqueEmail = 1,
#PasswordFormat = 1,
#UserId = #UserId OUTPUT
SELECT #UserId as N'#UserId'
SELECT 'Return Value' = #return_value
And add the rols you need. 'sitecore\Sitecore Client Users' is the rol you need to login into the CMS.
EXECUTE [dbo].[aspnet_UsersInRoles_AddUsersToRoles]
#ApplicationName = N'sitecore'
,#UserNames = N'sitecore\startup'
,#RoleNames = N'sitecore\Sitecore Client Users'
,#CurrentTimeUtc = N'2017-03-03'
GO
This example create a user 'startup' with password 'mypassword' with minimal rights.
You can now use Sitecore Powershell extensions to create users in Sitecore:
example
PS master:\> New-User -Identity michael -Enabled -Password b -Email batman#gmail.com -FullName "Bruce Wayne"
Related
Some time ago I wrote a simple python app which asks users for input and generates a new mail via Outlook app basing on the input. Now, I was asked to add some functionality so the app will no longer generate a new mail but it'll forward a selected email and add content to it. While I was able to write code which generates a new mail, I'm completely lost when I want to approach it with forwarding selected mails.
At the moment I use something like this to send a new email:
import win32com.client
from win32com.client import Dispatch
const=win32com.client.constants
olMailItem = 0x0
obj = win32com.client.Dispatch("Outlook.Application")
newMail = obj.CreateItem(olMailItem)
newMail.SentOnBehalfOfName = 'mail#mail.com'
newMail.Subject = ""
newMail.BodyFormat = 2
newMail.HTMLBody = output
newMail.To = ""
newMail.CC = ""
newMail.display()
And I know that by using something like this you can select an email in Outlook so Python can interact with it :
obj = win32com.client.Dispatch("Outlook.Application")
selection = obj.ActiveExplorer().Selection
How to merge these two together so the app will forward a selected email and add a new content on the top? I tried to find it out by trial and error, but finally, I gave up. Microsoft API documentation also was not very helpful for me as I was not really able to understand much of it (I'm not a dev). Any help appreciated.
Replace the line newMail = obj.CreateItem(olMailItem) with
newMail = obj.ActiveExplorer().Selection.Item(1).Forward()
Hi I am new to laravel but I would like to load all the bookings for the currently logged in user.
I have tried doing this
//check if user is logged in
if ($user = Auth::user()) {
//get only the bookings for the currently logged in user
$allProducts =Booking::where('client', Auth::user()->name)->where('name', $name)->first();
//store the bookings in a products variable
$products = json_decode(json_encode($allProducts));
//Loop through the products:
foreach ($products as $key => $val) {
//get the name of the service by matching it's id in the service model to the service column in the products
$service_name = Service::where(['id' => $val->service])->first();
//get the charge amount of the service by matching it's id in the Charge model to the charge column in the products
$service_fee = Charge::where(['id' => $val->charge])->first();
//get the status of the service by matching it's id in the status model to the status column in the products
$service_status = Status::where(['id' => $val->status])->first();
$products[$key]->service_name = $service_name->name;
$products[$key]->service_fee = $service_fee->total;
$products[$key]->service_status = $service_status->name;
}
return view('client.booking.view_bookings')->with(compact('products'));
}
return view('/login');
}
But that is giving me an error: Undefined variable: name on the line
$allProducts =Booking::where('client', Auth::user()->name)->where('name', $name)->first();
What could I be doing wrong? and how can I solve it to dsplay only the required data
I have tried to understand what you are doing without success but from your explanations in the comments, I think I know what you want to do.
Since you said that this code works well for you except that it gives you the results of all the data in the database irrespective of the logged in user
$allProducts = Booking::get();
it is because that creates a query that selects all the data in the database.
Whatv you need is to add a where clause to your statement. to do that simply add this to the above line of code
where('client', Auth::user()->name)
it will return only the data that that contains the client column equal to the name of the currently logged in user.
Therefore the entire line of code becomes;
$allProducts = Booking::get()->where('client', Auth::user()->name);
Alternatively you could use filters
I've followed the guide in the queryset documentation as per (https://docs.djangoproject.com/en/1.10/ref/models/querysets/#update-or-create) but I think im getting something wrong:
my script checks against an inbox for maintenance emails from our ISP, and then sends us a calendar invite if you are subscribed and adds maintenance to the database.
Sometimes we get updates on already planned maintenance, of which i then need to update the database with the new date and time, so im trying to use "update or create" for the queryset, and need to use the ref no from the email to update or create the record
#Maintenance
if sender.lower() == 'maintenance#isp.com':
print 'Found maintenance in mail: {0}'.format(subject)
content = Message.getBody(mail)
postcodes = re.findall(r"[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][A-Z]{2}", content)
if postcodes:
print 'Found Postcodes'
else:
error_body = """
Email titled: {0}
With content: {1}
Failed processing, could not find any postcodes in the email
""".format(subject,content)
SendMail(authentication,site_admins,'Unprocessed Email',error_body)
Message.markAsRead(mail)
continue
times = re.findall("\d{2}/\d{2}/\d{4} \d{2}:\d{2}", content)
if times:
print 'Found event Times'
e_start_time = datetime.strftime(datetime.strptime(times[0], "%d/%m/%Y %H:%M"),"%Y-%m-%dT%H:%M:%SZ")
e_end_time = datetime.strftime(datetime.strptime(times[1], "%d/%m/%Y %H:%M"),"%Y-%m-%dT%H:%M:%SZ")
subscribers = []
clauses = (Q(site_data__address__icontains=p) for p in postcodes)
query = reduce(operator.or_, clauses)
sites = Circuits.objects.filter(query).filter(circuit_type='MPLS', provider='KCOM')
subject_text = "Maintenance: "
m_ref = re.search('\[(.*?)\]',subject).group(1)
if not len(sites):
#try use first part of postcode
h_pcode = postcodes[0].split(' ')
sites = Circuits.objects.filter(site_data__postcode__startswith=h_pcode[0]).filter(circuit_type='MPLS', provider='KCOM')
if not len(sites):
#still cant find a site, send error
error_body = """
Email titled: {0}
With content: {1}
I have found a postcode, but could not find any matching sites to assign this maintenance too, therefore no meeting has been sent
""".format(subject,content)
SendMail(authentication,site_admins,'Unprocessed Email',error_body)
Message.markAsRead(mail)
continue
else:
#have site(s) send an invite and create record
for s in sites:
create record in circuit maintenance
maint = CircuitMaintenance(
circuit = s,
ref = m_ref,
start_time = e_start_time,
end_time = e_end_time,
notes = content
)
maint, CircuitMaintenance.objects.update_or_create(ref=m_ref)
#create subscribers for maintenance
m_ref, is the unique field that will match the update, but everytime I run this in tests I get
sites_circuitmaintenance.start_time may not be NULL
but I've set it?
If you want to update certain fields provided that a record with certain values exists, you need to explicitly provide the defaults as well as the field names.
Your code should look like this:
CircuitMaintenance.objects.update_or_create(default=
{'circuit' : s,'start_time' : e_start_time,'end_time' : e_end_time,'notes' : content}, ref=m_ref)
The particular error you are seeing is because update_or_create is creating an object because one with rer=m_ref does not exist. But you are not passing in values for all the not null fields. The above code will fi that.
I am trying to get the following connection to our LDAP working via ColdFusion, however, I can never get it to return any values (i.e. results.recordcount always equals 0). I assume my problem is with the "start" portion of the query so I did some research and have tried numerous values but nothing seems to work.
<cfldap
server = "adserver"
action = "query"
username = "DOMAIN\username"
password = "apassword"
name = "results"
scope="subtree"
start = "dc=domain.local"
attributes = "givenname,surname,uid,userid,groupMembership,mail,dn,roles,memberof,cn,samaccountName">
<cfoutput>
#results.recordcount#
</cfoutput>
The structure of the AD that I'm trying to access is as follows. I'm trying to get to the "Users" section at the bottom of the tree shown.
Active Directory Users and Computers
- Saved queries
- domain.local
- option1
- option2
- NAME1
- option1
- option2
- NAME2
- Computers
- Disabled Users
- Groups
- Users
If I right-click on "User" and view the properties it tells me the canonical name for it is domain.local/NAME1/NAME2/Users, which I assume is relevant to my problem.
Any ideas what I should be using for the "start" portion of cfldap?
Thanks in advance.
I highly recommend browsing your AD with a program like Softerra's LDAP Browser (http://www.ldapbrowser.com/) and then locating the distinguished name of the hierarchy where you want to start searching. Using this, I was able to find the exact DN of the LDAP structure to target.
Try somethign like this. I've had the best luck starting at a high level and then using the filter attribute to drill down.
<cfldap action="query" start="DC=server, DC=domain, DC=com" filter="OU=Users"
username = "DOMAIN\username" password = "apassword" name = "results"
scope="subtree" attributes = "givenname,surname,uid,userid,groupMembership,mail,dn,roles,memberof,cn,samaccountName">
I'm using Django registration inside my project on a development server.
When I register a new user, I use EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend' to get the activation link.
When I try to put the activation link into the web browser, I have an error, and the account is not activated.
It is said :
Thank you.
This function is used to generate the key.
def create_profile(self, user):
"""
Create a ``RegistrationProfile`` for a given
``User``, and return the ``RegistrationProfile``.
The activation key for the ``RegistrationProfile`` will be a
SHA1 hash, generated from a combination of the ``User``'s
username and a random salt.
"""
salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
username = user.username
if isinstance(username, unicode):
username = username.encode('utf-8')
activation_key = hashlib.sha1(salt+username).hexdigest()
return self.create(user=user,
activation_key=activation_key)
I received that mail. But I use EMAIL_BACKEND'django.core.mail.backends.filebased.EmailBackend'.
I think the problem comes from here. But I can't test in production server.
I solved the problem actually It's because I generate the email to send inside a file thanks to the file email backends provided by django for development purpose. Inside this file, when there is a carriage return, it adds an = characters. And this is the case with the link to active the account.
You shouldn't have a = character in your activation key.
Although sergzach's answer will work, I'd be more interested in finding out why that = is there in the first place.
django-registration usually generates the key as follows:
salt = sha.new(str(random.random())).hexdigest()[:5]
activation_key = sha.new(salt+user.username).hexdigest()
Where are you generating yours?
The character '=' is not in the range of \w+. Use [\w=]+ instead of \w+.
Replace ?P<activation_key>\w+ to ?P<activation_key>[\w=]+