Spring security Freemarker Session is null or missing - spring-security

I'm trying to use Session object in Freemarker template:
<#assign
known = Session.SPRING_SECURITY_CONTEXT??
>
<#if known>
<#assign
user = Session.SPRING_SECURITY_CONTEXT.authentication.principal
name = user.getUsername()
isAdmin = user.isAdmin()
currentUserId = user.getId()
>
<#else>
<#assign
name = "unknown"
isAdmin = false
currentUserId = -1
>
</#if>
but receive the error:
freemarker.core.InvalidReferenceException: The following has evaluated to null or missing:
==> Session [in template "parts/security.ftlh" at line 2, column 9]
How could I use the Session object in Freemarker? Is another method exists to hide some HTML elements based on user roles?

Add spring.freemarker.expose-session-attributes=true to the application.properties
And modify your code to:
<#assign
known = SPRING_SECURITY_CONTEXT??
>
<#if known>
<#assign
user = SPRING_SECURITY_CONTEXT.authentication.principal
name = user.getUsername()
isAdmin = user.isAdmin()
currentUserId = user.getId()
>
<#else>
<#assign
name = "unknown"
isAdmin = false
currentUserId = -1
>
</#if>

Related

GoogleAds conversion action with custom value

I'm try to create new conversion action that the value in UI will be "Use different values for each conversion"
I'm using add_conversion_action.py from example.
In the value_settings I set:
value_settings.default_value = 0.0
value_settings.always_use_default_value = True
But in the UI I got "Don't use a value for this conversion action (not recommended)"
I try to look for answer on developers.google but all looks fine.
Thanks!
The code from example:
# [START add_conversion_action]
def main(client, customer_id):
conversion_action_service = client.get_service("ConversionActionService")
# Create the operation.
conversion_action_operation = client.get_type("ConversionActionOperation")
# Create conversion action.
conversion_action = conversion_action_operation.create
conversion_action.name = f"Earth to Mars Cruises Conversion {uuid.uuid4()}"
conversion_action.type_ = (
client.enums.ConversionActionTypeEnum.UPLOAD_CLICKS
)
conversion_action.category = (
client.enums.ConversionActionCategoryEnum.DEFAULT
)
conversion_action.status = client.enums.ConversionActionStatusEnum.ENABLED
conversion_action.view_through_lookback_window_days = 15
# Create a value settings object.
value_settings = conversion_action.value_settings
value_settings.default_value = 0.0
value_settings.always_use_default_value = True
# Add the conversion action.
conversion_action_response = (
conversion_action_service.mutate_conversion_actions(
customer_id=customer_id,
operations=[conversion_action_operation],
)
)
print(
"Created conversion action "
f'"{conversion_action_response.results[0].resource_name}".'
)
# [END add_conversion_action]
Because you used
value_settings.default_value = 0.0
value_settings.always_use_default_value = True
To set "Use different values for each conversion", value_settings.always_use_default_value must be False.
value_settings.always_use_default_value = False

Do not include the database column when query string is NULL

I'm trying to make a search functionality. The code below says that if Port, Status and TIN are not null then query the database.
E.g 1. If User has chosen the port and status but not the TIN then the
TIN should not be included when searching the database.
E.g 2. If User has chosen the port only then the Status and TIN should
not be included when searching the database.
Code
int Port = Convert.ToInt32(Request.QueryString["Port"]);
var Status = Request.QueryString["Status"];
var TIN = Request.QueryString["TIN"];
List<Transaction> QueriedTransactionList;
QueriedTransactionList = db.Transactions.ToList();
TransactionViewModel TransactionViewModel = new TransactionViewModel();
List<TransactionViewModel> TransactionDataList = QueriedTransactionList.Select(x => new TransactionViewModel{
TTransactionID = x.TTransactionID,
BatchID = x.BatchID,
TransactionDateTime = x.TransactionDateTime,
TransactionStatus = x.TransactionStatus,
TaxPayerName = x.Card.TaxPayer.TaxPayerName,
TaxPayerEmail = x.Card.TaxPayer.TaxPayerEmail,
TaxPayerTIN = x.Card.TaxPayer.TaxPayerTIN,
DispatchBy = x.User.UserName,
DestinationPort = x.Card.Port.PortName,
BatchCards = Helper.GetBatchQtyByBatchID(x.BatchID)
}).GroupBy(x => x.BatchID).Select(x => x.LastOrDefault()).Where(x => Status.IndexOf(x.TransactionStatus, StringComparison.OrdinalIgnoreCase) >= 0 && TIN.IndexOf(x.Card.TaxPayerTIN, StringComparison.OrdinalIgnoreCase) >= 0).OrderByDescending(x => x.TTransactionID).ToList();

IE11 clears password fields on page refresh:

Happens only in IE (Chrome and Firefox, no issues... go figure)
I have a page where customer's can update their details (name, address,password etc.) and everything is working fine, however if the customer submits the form (which also works fine) and then presses the back button all the customer's information will repopulate the form except for the password field.
My boss would like this to repopulate as well, like it does in Chrome and Firefox, but IE won't do it. I'm hoping it's something simple I've missed but I can't see it. I've tried adjusting the lines where the text fields are populated to match the rest of the form, but that just results in empty fields. Code below.
Page_Load
If TypeOf Session("Customer") Is GPCUser Then
c = CType(Session("Customer"), GPCUser)
Else
Response.Redirect("default.aspx")
End If
If Not Page.IsPostBack Then
If c.CustomerID > 0 Then
'populate the table
lblAccountName.Text = c.AccountName
txtFirstName.Text = c.FirstName
txtLastName.Text = c.LastName
txtEmail.Text = c.Email
txtAddress.Text = c.Address
txtSuburb.Text = c.Suburb
txtCityTown.Text = c.City
txtPostcode.Text = c.PostCode
txtPhone.Text = c.Phone
txtMobile.Text = c.Mobile
'chkNewsletter.checked = c.Newsletter
txtPassword.Attributes.Add("value", c.GeneratedPassword)
txtConfirmPassword.Attributes.Add("value", c.GeneratedPassword)
'txtPassword.Text = c.GeneratedPassword
'txtConfirmPassword.Text = c.GeneratedPassword
Dim subscriptions As ContactSubscriptions = New ContactSubscriptions(c.CustomerID)
chkGenernalNewsletters.Checked = subscriptions.IsGenernalNewsletters
End If
Else
End If
Update Button
If TypeOf Session("Customer") Is GPCUser Then
c = CType(Session("Customer"), GPCUser)
Else
Exit Sub
End If
c.AccountName = lblAccountName.Text
c.FirstName = txtFirstName.Text
c.LastName = txtLastName.Text
c.Email = txtEmail.Text
c.Address = txtAddress.Text
c.Suburb = txtSuburb.Text
c.City = txtCityTown.Text
c.PostCode = txtPostcode.Text
c.Phone = txtPhone.Text
c.Mobile = txtMobile.Text
'c.Newsletter = chkNewsletter.Checked
c.GeneratedPassword = txtPassword.Text
c.CustomerUpdatedRequired = false
'Update password field
txtPassword.Attributes.Add("value", c.GeneratedPassword)
txtConfirmPassword.Attributes.Add("value", c.GeneratedPassword)
GPCUser.AddUpdateCustomer(c)
subscriptions.IsGenernalNewsletters = chkGenernalNewsletters.Checked
subscriptions.Save()
Session("Customer") = c
lblMessage.Text = "Your details have been successfully updated."
pnlUpdateAccount.Visible = False

Wrong Number of Arguments

I understand what causes the wrong number of arguments error but my code doesn't pass any parameters to initialize any of the classes so I'm not sure at all why my code is giving me this error. I'm also pretty new to Ruby on Rails so that doesn't help things. My code is below:
def create_google_file
#products = Product.find(:all)
file = File.new('dir.xml','w')
doc = REXML::Document.new
root = REXML::Element.new "rss"
root.add_attribute("xmlns:g", "http://base.google.com/ns/1.0")
root.add_attribute("version", "2.0")
channel = REXML::Element.new "channel"
root.add_element channel
title = REXML::Element.new "title"
title.text = "Sample Google Base"
channel.add_element title
link = REXML::Element.new "link"
link.text = "http://base.google.com/base/"
channel.add_element link
description = REXML::Element.new "description"
description.text = "Information about products"
channel.add_element description
#products.each do |y|
item = channel.add_element("item")
id = item.add_element("g:id")
id.text = y.id
title = item.add_element("title")
title.text = y.title
description = item.add_element("description")
description.text = y.description
googlecategory = item.add_element("g:google_product_category")
googlecategory.text = y.googlecategory
producttype = item.add_element("g:product_type")
producttype.text = y.producttype
link = item.add_element("link")
link.text = y.link
imglink = item.add_element("g:image_link")
imglink.text = y.imglink
condition = item.add_element("condition")
condition.text = y.condition
availability = item.add_element("g:availability")
availability.text = y.availability
price = item.add_element("g:price")
price.text = y.price "USD"
gtin = item.add_element("g:gtin")
gtin.text = y.gtin
brand = item.add_element("g:brand")
brand.text = y.brand
mpn = item.add_element("g:mpn")
mpn.text = y.mpn
expirationdate = item.add_element("g:expiration_date")
expirationdate.text = y.salepricedate
end
doc.add_element root
file.puts doc
file.close
end
The error I'm getting is:
ArgumentError in ProductsController#create_google_file
wrong number of arguments (1 for 0)
At the request of the poster, I am putting my comments in to an answer:
Based purely on the consistency of the other lines, but without knowing which line is actually failing, it may be this part: price.text = y.price "USD". Is y.price a method that takes in a parameter? Is it defined as def price(type) or something? If not, if it doesn't take any parameters, then it's because you're not supposed to send any parameters to that method. It looks like it's just a getter.
#FranklinJosephMoormann As I suspected, that's the line. Were you trying to make a string like "4.50 USD"? Then you probably wanted: price.text = "#{y.price} USD". That will take the result of y.price and put it in a string, and allow you to keep typing more in the string. It's called string interpolation.

issue getting dynamic Config parameter in Grails taglib

I have a dynamic config parameter I want to get like:
String srcProperty = "${attrs ['src']}.audio" + ((attrs['locale'])? "_${attrs['locale']}" : '')
assert srcProperty == "prompt.welcomeMessageOverrideGreeting.audio"
where my config has:
prompt{
welcomeMessageOverrideGreeting {
audio = "/en/someFileName.wav"
txt = "Text alternative for /en/someFileName.wav"
audio_es = "/es/promptFileName.wav"
txt_es = "Texto alternativo para /es/someFileName.wav"
}
}
While this works fine:
String audio = "${config.prompt.welcomeMessageOverrideGreeting.audio}"
and:
assert "${config.prompt.welcomeMessageOverrideGreeting.audio}" == "/en/someFileName.wav"
I can not get this to work:
String audio = config.getProperty("prompt.welcomeMessageOverrideGreeting.audio")
They're not stored flat like that, they're stored hierarchically. "config.prompt.welcomeMessageOverrideGreeting.audio" is a shorthand to get "prompt" from config, then "welcomeMessageOverrideGreeting" from that, then "audio" from that. If you want to use dot notation just flatten the config:
String audio = config.flatten().getProperty("prompt.welcomeMessageOverrideGreeting.audio")
SOLVED: This was REALLY tough, but here is what I found that worked to get a dynamic property:
String audio = srcProperty.tokenize( '.' ).inject( config ) { cfg, pr -> cfg[ pr ] }
I blogged about it:
http://www.baselogic.com/blog/development/grails-groovy-development/configslurper-with-dynamic-property-name-from-configurationholder-config-object
Assuming myconfig.groovy in classpath:
prompt{
welcomeMessageOverrideGreeting {
audio = "/en/someFileName.wav"
txt = "Text alternative for /en/someFileName.wav"
audio_es = "/es/promptFileName.wav"
txt_es = "Texto alternativo para /es/someFileName.wav"
}
}
We can get properties constructing their names dynamically:
def myconfig = this.class.getResource("/myconfig.groovy")
def config = new ConfigSlurper().parse(myconfig)
def dynamic = "welcomeMessageOverrideGreeting"
def dynamic2 = "audio"
def locale = "es"
assert config.prompt[dynamic].audio == "/en/someFileName.wav"
assert config.prompt.welcomeMessageOverrideGreeting[dynamic2] == "/en/someFileName.wav"
assert config.prompt.welcomeMessageOverrideGreeting["${dynamic2}_${locale}"] == "/es/promptFileName.wav"
assert config.prompt[dynamic]["${dynamic2}_${locale}"] == "/es/promptFileName.wav"

Resources