Thursday, June 28, 2012

Using Schema.getGlobalDescribe() to get list of all fields in Apex


        For Example, We have one dropdown that had options – Lead, Account, Contact, Opportunities and some custom objects. Upon selection of any of this object, all the respective object’s standard and custom fields should be populated in another dropdown. 
This is how we can do it:
Map<String, Schema.SObjectField> objectFields = Schema.getGlobalDescribe().get(‘Account’).getDescribe().fields.getMap();
for(String s : objectFields.keySet())
{
      // process s
}

Sunday, June 3, 2012

Salesforce Security


Security Overview:
          Salesforce is built with security as the foundation for the entire service. This foundation includes both protection for your data and applications, and the ability to implement your own security scheme to reflect the structure and needs of your organization.
          The security features of Salesforce provide both strength and flexibility. However, protecting your data is a joint responsibility between you and salesforce.com. The security features in Salesforce enable you to empower your users to do their jobs efficiently, while also limiting exposure of data to the users that need to act upon it. Implement security controls that you think are appropriate for the sensitivity of your data. Your data is protected from unauthorized access from outside your company, and you should also safeguard it from inappropriate usage by your users.
Security Infrastructure:
          One of the core features of a multi-tenant platform is the use of a single pool of computing resources to service the needs of many different customers. Salesforce protects your organization's data from all other customer organizations by using a unique organization identifier, which is associated with each user's session. Once you log in to your organization, your subsequent requests are associated with your organization, using this identifier.
                    Salesforce utilizes some of the most advanced technology for Internet security available today. When you access the application using a Salesforce-supported browser, Secure Socket Layer (SSL) technology protects your information using both server authentication and data encryption, ensuring that your data is safe, secure, and available only to registered users in your organization.
User security:
          Salesforce provides each user in your organization with a unique username and password that must be entered each time a user logs in. Salesforce issues a session cookie only to record encrypted authentication information for the duration of a specific session. The session cookie does not include either the username or password of the user. Salesforce does not use cookies to store other confidential user and session information, but instead implements more advanced security methods based on dynamic data and encoded session IDs.
About passwords:
There are several settings you can configure to ensure that your user's passwords are strong and secure:
·       Password policies—set various password and login policies, such as specifying    an amount of time before all users' passwords expire, the level of complexity required for passwords, and so on.
·       User password expiration—expire the passwords for all the users in your organization (except for users with “Password Never Expires” permission.)
·       User password resets—reset the password for specified users.
·       Login attempts and lockout periods—if a user is locked out of Salesforce due to too many failed login attempts, you can unlock them.
Password requirements:
       A password cannot contain your User Name and cannot match your first or last name.
For all editions, a new organization has the following default password requirements:
·       A password must contain at least eight characters.
·       A password must contain at least one alphabetic character and one number.
·       The answer to the question posed if you forget your password cannot contain   your password.
·       The last three passwords are remembered and cannot be reused when you are changing your password.

User authentication:
          Salesforce has its own system of user authentication, but some companies prefer to use an existing single sign-on capability to simplify and standardize their user authentication. You have two options to implement single sign-on—federated authentication using Security Assertion Markup Language (SAML) or delegated authentication.


§  Federated authentication using Security Assertion Markup Language (SAML) allows you to send authentication and authorization data between affiliated but unrelated Web services. This enables you to sign-on to Salesforce from a client application. Federated authentication using SAML is enabled by default for your organization.
§  Delegated authentication single sign-on enables you to integrate Salesforce with an authentication method that you choose. This enables you to integrate authentication with your LDAP (Lightweight Directory Access Protocol) server, or perform single sign-on by authenticating using a token instead of a password. You manage delegated authentication at the profile level, allowing some users to use delegated authentication, while other users continue to use their Salesforce-managed password. Delegated authentication is set by profile, not organization wide. You must request that this feature be enabled by salesforce.com. Contact salesforce.com to enable delegated authentication single sign-on for your organization.
The primary reasons for using delegated authentication include:
·       Using a stronger type of user authentication, such as integration with a secure identity provider
·       Making your login page private and not part of the general Internet, but rather, part of your corporate network, behind your corporate firewall
·       Differentiating your organization from all other organizations that use Salesforce in order to reduce phishing attacks.

Network-based Security:
          User authentication determines who can log in, while network-based security limits where they can log in from and when. Use network-based security to limit the window of opportunity for an attacker by restricting the origin of user logins. Network-based security can also make it more difficult for an attacker to use stolen credentials.
          To enhance network-based security, Salesforce includes the ability to restrict the hours during which users can log in and the range of IP addresses from which they can log in. If IP address restrictions are defined for a user's profile and a login originates from an unknown IP address, Salesforce does not allow the login. This helps to protect your data from unauthorized access and “phishing” attacks.
          To set the organization-wide list of trusted IP addresses from which users can always log in without a login challenge. To restrict login hours by profile, or to restrict logins by IP addresses for specific profiles.
Session Security:
          After logging in, a user establishes a session with the platform. Use session security to limit exposure to your network when a user leaves their computer unattended while still logged on. It also limits the risk of internal attacks, such as when one employee tries to use another employee's session.
          You can control the session expiration time window for user logins. Session expiration allows you to select a timeout for user sessions. The default session timeout is two hours of inactivity. When the session timeout is reached, users are prompted with a dialog that allows them to log out or continue working. If they do not respond to this prompt, they are automatically logged out.
Securing Data Access:
Choosing the data set that each user or group of users can see is one of the key decisions that affects data security. You need to find a balance between limiting access to data, thereby limiting risk of stolen or misused data, versus the convenience of data access for your users.
To enable users to do their job without exposing data that they do not need to see, Salesforce provides a flexible, layered sharing design that allows you to expose different data sets to different sets of users.
§  To specify the objects that users can access, you can assign profiles.
§  To specify the fields that users can access, you can use field-level security.
§  To specify the individual records that users can view and edit, you can set your organization-wide sharing settings, define a role hierarchy, and create sharing rules.
The following describes these security and sharing settings:
Object-level security provides the bluntest way to control data. Using object-level security you can prevent a user from seeing, creating, editing, or deleting any instance of a particular type of object, such as a lead or opportunity. Object-level security lets you hide whole tabs and objects from particular users, so that they don't even know that type of data exists.
          You specify object-level security settings in profiles. A profile is a collection of settings and permissions that determine what a user can do in the application, similar to a group in a Windows network, where all of the members of the group have the same folder permissions and access to the same software.
          Profiles are typically defined by a user's job function (for example, system administrator or sales representative), but you can have profiles for anything that makes sense for your organization. A profile can be assigned to many users, but a user can be assigned to only one profile at a time. It's worth taking time up-front to align your various user sets with profiles, depending on what they need to see and do in the application.
In some cases, you may want users to have access to an object, but limit their access to individual fields in that object. Field-level security controls whether a user can see, edit, and delete the value for a particular field on an object. It lets you protect sensitive fields without having to hide the whole object from users. Field-level security is also controlled in profiles.
Unlike page layouts, which only control the visibility of fields on detail and edit pages, field-level security controls the visibility of fields in any part of the app, including related lists, list views, reports, and search results. To ensure that a user can't access a particular field, use field-level security settings. No other settings provide the same level of protection for a field. Important
Field-level security doesn't prevent searching on the values in a field. To set up your organization to prevent users from searching and retrieving records that match a value in a field hidden by field-level security, contact salesforce.com Customer Support.
Record-Level Security (Sharing)
After setting object- and field-level access permissions, you may want to configure access settings for the actual records themselves. Record-level security lets you give users access to some object records, but not others. Every record is owned by a user or a queue. The owner has full access to the record. In a hierarchy, users higher in the hierarchy (such as managers in a role hierarchy) always have access to the data visible to users below them in the hierarchy. This access applies to records owned by users, as well as records shared with them.
          To specify record-level security, set your organization-wide sharing settings, define a hierarchy, and create sharing rules.
§  Organization-wide sharing settings—The first step in record-level security is to determine the organization-wide sharing settings for each object. Organization-wide sharing settings specify the default level of access users have to each others' records.
You use organization-wide sharing settings to lock down your data to the most restrictive level, and then use the other record-level security and sharing tools to selectively give access to other users. For example, let's say users have object-level permissions to read and edit opportunities, and the organization-wide sharing setting is Read-Only. By default, those users can read all opportunity records, but can't edit any unless they own the record or are granted additional permissions.
§  Role hierarchy—Once you've specified organization-wide sharing settings, the first way you can give wider access to records is with a role hierarchy. Similar to an organization chart, a role hierarchy represents a level of data access that a user or group of users needs. The role hierarchy ensures that managers always have access to the same data as their employees, regardless of the organization-wide default settings. Role hierarchies don't have to match your organization chart exactly. Instead, each role in the hierarchy should represent a level of data access that a user or group of users needs.
You can also use a territory hierarchy to share access to records. A territory hierarchy grants users access to records based on criteria such as zip code, industry, revenue, or a custom field that is relevant to your business. For example, you could create a territory hierarchy in which a user with the “North America” role has access to different data than users with the “Canada” and “United States” roles.
Note:
     Although it's easy to confuse profiles with roles, they control two very different things. Profiles control a user's object- and field-level access permissions. Roles primarily control a user's record-level access through role hierarchy and sharing rules.
§  Sharing rules—Sharing rules let you make automatic exceptions to organization-wide sharing settings for particular sets of users, to give them access to records they don't own or can't normally see. Sharing rules, like role hierarchies, are only used to give additional users access to records—they can't be stricter than your organization-wide default settings.
§  Manual sharingSometimes it's impossible to define a consistent group of users who need access to a particular set of records. In those situations, record owners can use manual sharing to give read and edit permissions to users who would not have access to the record any other way. Although manual sharing isn't automated like organization-wide sharing settings, role hierarchies, or sharing rules, it gives record owners the flexibility to share particular records with users that need to see them.
§  Apex managed sharing—If sharing rules and manual sharing don't give you the control you need, you can use Apex managed sharing. Apex managed sharing allows developers to programmatically share custom objects. When you use Apex managed sharing to share a custom object, only users with the “Modify All Data” permission can add or change the sharing on the custom object's record, and the sharing access is maintained across record owner changes.
Creating Predefined Case Teams and Assigning Case Teams to Cases using APEX


Trigger to Create Case Team Member Role:

Trigger CreateMemberRole on user (before insert,before update)
{
caseteamrole cr=new caseteamrole();
cr.accesslevel='edit';
cr.name='test';
cr. PreferencesVisibleInCSP=true;
insert(cr);
}

Trigger to Create Predefined Case Team:

trigger CreateCaseTeam on User (before insert,before update) 
{
caseteamtemplate ct;
caseteamrole cr;
caseteamtemplate c;
try{
cr=[select id from caseteamrole where name=:'test'];
ct=[select id,name from caseteamtemplate where name=:'test'];
c=ct;
}
catch(Exception e)
{
if(ct==null)
{
//create case team template
c=new caseteamtemplate(); 
c.Description='test';
c.Name='test';
insert(c);
}
}
//add case team member to pre defined case team
caseteamtemplatemember cm=new caseteamtemplatemember();
cm.memberid=trigger.new[0].id;
cm.teamroleid=cr.id;
cm.teamtemplateid=c.id;
insert(cm);
}

caseteamtemplaterecord cttr=new caseteamtemplaterecord();
cttr.parentid=trigger.new[0].id;
caseteamtemplate ct=[select id from caseteamtemplate where name=:'test'];
cttr.teamtemplateid=ct.id;
}


Assigning Case Team to a Case:

Trigger AssignToCase on user (before insert,before update)
{
caseteamrole cr=new caseteamrole();
cr.accesslevel='edit';
cr.name='test';
cr. PreferencesVisibleInCSP=true;
insert(cr);
}